Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inputing text in textbox

Can anyone please tell me why this jsFiddle doesn't work?

The idea is simple is just suppose to input the selected text into the textbox..

HTML:

<input type="text" id="teste" maxlength="50">
<select>
    <option onClick="nelson">nelson</option>
</select>

JavaScript:

function nelson(){
    document.getElementById('teste').value =+ "nelson"; 
}

Thanks in advance

like image 335
Alpha Avatar asked Dec 02 '22 22:12

Alpha


1 Answers

DEMO: jsFiddle

HTML:

<input type="text" id="teste" maxlength="50" />
<select onchange="selectedItemChange(this)">
    <option value="nelson">nelson</option>
    <option value="justin">justin</option>
</select>

JS:

function selectedItemChange(sel) {
    document.getElementById('teste').value = sel.value;
}

Explanation:

<option onClick="nelson">nelson</option>
  • was changed for three reasons:

    1. onclick is preferred to onClick for consistency
    2. nelson needed to be changed to nelson() to actually call the function.
    3. Since we are dealing with a select html element it is better to use the onchange event on the root.

document.getElementById('teste').value =+ "nelson";

  • As many others have pointed out the proper operator is += or =

To set initial value do the following

DEMO: jsFiddle

HTML

<input type="text" id="teste" maxlength="50" />
<select id="select-people" onchange="selectedItemChange(this)">
    <option value="nelson">nelson</option>
    <option value="justin">justin</option>
</select>

JS

function selectedItemChange(sel) {
    document.getElementById('teste').value = sel.value;
}

window.onload=function(){
    document.getElementById('teste').value = document.getElementById("select-people").value;
}
like image 173
abc123 Avatar answered Dec 13 '22 03:12

abc123