Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an element by name and set its value

There should 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?

like image 445
Stephen305 Avatar asked Apr 26 '12 18:04

Stephen305


2 Answers

Description

You are mixing normal javascript and jQuery. Use the attribute selector.

Check out my sample and this jsFiddle Demonstration

Sample

Html

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

jQuery

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

Edit

If you want, for some reason, change a element which name is a value in another element then do this. jsFiddle Demonstration

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");
});​

More Information

  • jQuery - Attribute Equals Selector [name="value"]
  • jsFiddle Demonstration (first sample)
  • jsFiddle Demonstration (second sample)
like image 197
dknaack Avatar answered Oct 20 '22 15:10

dknaack


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

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

like image 34
ajax333221 Avatar answered Oct 20 '22 15:10

ajax333221