1

$("[name=imageheight]") return following array of textboxes

enter image description here

I know i can get the value of textbox by its index like

enter image description here

How do i set the value of textbox on index 0. i have tried this but it gives me a error

enter image description here

Muzafar Khan
  • 826
  • 3
  • 15
  • 28

6 Answers6

1
$('[name=imageheight]').eq(0).attr('value', '250')
Gynteniuxas
  • 7,035
  • 18
  • 38
  • 54
Muzafar Khan
  • 826
  • 3
  • 15
  • 28
0

you can use

$('[name=imageheight]').eq(0).val(250)
0

Explanation:

jQuery returns a jQuery object which has a val function, which returns its value if no parameter is passed and sets its value if a parameter is passed. However, the [0] of a jQuery object is an element and is not a jQuery object. As a result, it does not have a val() function. You can work with that as well, if you set its value attribute, like this:

jQuery("input[name=firstname]")[0].value = 250; Also, you can bypass jQuery if you want, like this:

document.querySelectorAll("input[name=firstname]")[0].value = 250;

Nitya Kumar
  • 967
  • 8
  • 14
0

The problem in your code is, $("[name=imageheight]")[0] will not return an jQuery object. So you cannot use .val() over that node. But, $("[name=imageheight]").eq(0) will return the node as a jQuery object over which you can use .val()

$('input').eq(0).val("new value")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70
0

Actually $("[name=imageheight]") returns jquery object of that element. that jquery object contains javascript DomElement object you can access DomElement object from jQuery object by $('....')[0]

$("[name=imageheight]")[0].value obviously return value because value is propert of DomElement.

You can set value by $("[name=imageheight]")[0].value= 250; in DomElement object

val() is setter and getter method of jQuery you have to fetch first element onlu by .first() method or ':first' selector.

$("[name=imageheight]:first").val(250);

or

$("[name=imageheight]").first().val(250);

Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
0

$('input').eq(0).val("new value")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />