user2968845
user2968845

Reputation: 11

setting the HTML textbox value based on the selected option using Javascript function. But it seems to be not working

This is the javascript snippet which assigns the selected option value to a text box

function check() {
 document.getElementById("inp").value=document.getElementById("id").value ;
} 

this is the actual html code

<form>
<select id="id"  onSelect="check( );">
<option></option>
<option value=85.5>opt1</option>
<option value=95.5>opt2</option>
<option value=95.5>opt3</option>
<option value=95.5>opt4</option>
</select>
<input type=text name="input" id="inp">
</form>

I Hope am done right ,but still am not able to get my solution

Upvotes: 1

Views: 12824

Answers (3)

MarsOne
MarsOne

Reputation: 2186

You HTML has multiple issues as well as your javascript

Your formatted HTML

<form>
<select id="id" onChange="check();">
    <option></option>
    <option value="85.5">opt1</option>
    <option value="95.5">opt2</option>
    <option value="95.5">opt3</option>
    <option value="95.5">opt4</option>
</select>
<input type="text" name="input" id="inp" />
</form>

JS

function check() {
    document.getElementById("inp").value = document.getElementById("id").value;
}

Working DEMO

Also you should enclose you values like value="". Besides this no major issues

Upvotes: 0

mplungjan
mplungjan

Reputation: 178421

Assuming this html

<select id="id">
  <option value="">Please select</option>
  <option value="85.5">opt1</option>
  <option value="95.5">opt2</option>
  <option value="95.5">opt3</option>
  <option value="95.5">opt4</option>
</select>

You can use unobtrusive JavaScript and add this to the head

Plain JS:

window.onload=function() { 
  document.getElementById("id").onchange=function() {     
    this.form.input.value=this.value; 
  }
}

Same in jQuery would be

$(function() { 
  $("#id").on("change",function() { 
    $("#inp").val($(this).val()); 
  }); 
}); 

If you MUST do it inline, then

<select id="id" onchange="this.form.input.value=this.value;">

Upvotes: 1

Nick
Nick

Reputation: 2907

Here's your fix.

This one works

I guess the summary of it is that you should change onSelect to onChange.

<script>
 function check() {
     document.getElementById("inp").value=document.getElementById("id").value;
    } 
 </script>
</head>
<body>
    <form>
        <select id="id"  onChange="check();">
        <option></option>
        <option value=85.5>opt1</option>
        <option value=95.5>opt2</option>
        <option value=95.5>opt3</option>
        <option value=95.5>opt4</option>
        </select>
    <input type=text name="input" id="inp" value="">
    </form>
</body>

Upvotes: 1

Related Questions