0

I have my code below. I've made an empty array, but I don't know how to connect them. Also I tried to get the value from my combo box, but it's giving me an error. The textbox tho takes the value from the user's input but not the combo box.

function sample() {
  var jsObject = [];
  jsObject {
    "salutation": null,
    "fname": null
  };
  var sal = document.getElementById('salutation').value;
  var fname = document.getElementById('fname').value;
  if (fname.value == "") {
    return false;
  }
  for (var key in sal) {
    sal = sal[key];
  }
}
<!DOCTYPE html>
<html>

<head>
  <title>Sample</title>
  <script type="text/javascript" src="index.js"></script>
</head>

<body>
  <form name="sam" onsubmit="return sample()" method="post">
    <select name="salutation">
    <option value="mr">Mr.</option>
    <option value="mrs">Mrs.</option>
    <option value="dr">Dr.</option>
   </select><br> Name:
    <br>
    <input type="text" name="fname" id="fname" required placeholder="Enter name">
    <input type="submit" onclick="sample(); return false;" value="Submit">
  </form>
</body>

</html>
  • 1
    You have syntax errors and you should not use forms + post if you're not actually sending any data to a server. Also, you call sample both with the button click and with the onsubmit event. – Shilly Mar 02 '17 at 14:51

1 Answers1

0

If you have a select element that looks like this:

<select id="ddlViewBy">
    <option value="1">test1</option>
    <option value="2" selected="selected">test2</option>
    <option value="3">test3</option>
</select>

Running this code:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;

Would make strUser be 2. If what you actually want is test2, then do this:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;

Which would make strUser be test2

Toxide82
  • 277
  • 1
  • 7
  • the original answer is here answered by @Paolo Bergantino[http://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript] – Toxide82 Mar 02 '17 at 14:51