How to get an element by name and set its value

There must be a simple solution for this. I need to get an input element by name and set its value.

The following Javascript does not work:

x = document.getElementsByName($('#questions').val()); x.value=this.value; 

Is there a simple solution using jQuery?

+6
source share
5 answers

Description

You mix plain javascript and jQuery. Use the attribute selector.

See my jsFiddle example and demo

Example

Html

 <input type="text" name="nameOfTheInputElement"/> 

JQuery

 $(function() { $("input[name='nameOfTheInputElement']").val("your value"); });​ 

Edit

If for some reason you want to change an element whose name is a value in another element, do this. jsFiddle Demo

Html

 <input type="text" id="questions" value="nameOfTheInputElement"/> <input type="text" name="nameOfTheInputElement"/> 

JQuery

 $(function() { var name = $("#questions").val(); $("input[name='"+name +"']").val("your value"); });​ 

Additional Information

+8
source

getElementsByName () returns node -list, so you need to get the first getElementsByName(...)[0]

But you are already using jQuery, so use it. Read some guides about jQuery selectors

+2
source

A simple, clean JavaScript (and therefore faster) solution:

 var x = document.getElementsByName(document.getElementById('questions').value)[0].value = this.value; 

I know that the jQuery tagline is "write less, do more," and in many cases this is true ... many cases !== always , though; -)

+1
source

try it

 var q = $("#question").val(); var x = $("input[name='" + q + "']").val(); 

in the second line, the q variable, the name represented at the input with id 'question', will be enclosed in 'and may contain any supported characters, such as space,:, - etc.

If you need the value of a component regardless of its tag, you can do this:

 var x = $("[name='" + q + "']").val(); 

Note that this approach $("[name='" + q + "']") can return more than one element, but .val() returns only the value of the first element.

+1
source

If I understand your question correctly, you want to get the element by name, and the name of the selected element will be indicated in the drop-down list or text area.

Here is my example:

Html

 <input type="text" id="enteredName"> <button id="doTheStuff">Do the work</button> <input name="one" value="One"> <input name="two" value="Two"> 

JQuery

 $('#doTheStuff').click(function(){ var objectOfInterest = $('[name=\'' + $('#enteredName').val() + '\']'); alert(objectOfInterest.val()); }); 

Working example

Here's another working example , using the drop-down list to specify a selection name.

0
source

Source: https://habr.com/ru/post/914257/


All Articles