I have many pair of text fields and submit button, with id
to submit button and class
to text field as same but different for each pair. So I want to pass the value entered in text field after button click to ajax function.
function update_rate(id){
// var price = document.getElementsByClassName(id)[0].innerHTML;
var price = document.getElementsByClassName(id);
console.log(price);
$.ajax({
type: "POST",
url: "update_rate.php", // Name of the php files
data: {subcategory : id , price: price},
success: function(res)
{
// console.log(html);
alert(res);
}
});
}
first pair:
<div class="form-group">
<input type="text" class="form-control" name="a" placeholder="Your task rate excl. taxes">
</div>
<button type="submit" id="a" onclick="update_rate(this.id)" class="btn btn-primary">Update</button>
<div class="form-group">
<input type="text" class="form-control" name="b" placeholder="Your task rate excl. taxes">
</div>
<button type="submit" id="b" onclick="update_rate(this.id)" class="btn btn-primary">Update</button>
But I can’t get the value of text field into variable.
3
Answers
Several things
var price = document.getElementsByClassName(id);
is plural and you need the value, so
var price = document.getElementsByClassName(id)[0].value;
if you mustBUT it is not a class. It is a name
var price = document.getElementsName(id)[0].value;
if you mustbut if you have jQuery, why not use it?
Here I take the button ID and find the input by name
I also change to type="button" – you do not want to submit when you use Ajax
As you’re already passing the id in the function, using jQuery, you can do something like:
This can and should be done in a different and more simple manner. Connecting the buttons with their text fields by
id
andclass
is not a scalable solution and requires constant updating of the code to keep all the naming in sync. Just get the value of the text field that comes just prior to the button. This will be easier if you modify your HTML structure so that the text field and the button are in the samediv
together.code into JavaScript.
it when it bubbles up to that element. This is called Event
Delegation.
.getElementsByClassName()
in 2020. Instead,use
.querySelector
.See comments below.
In the end, you have no
id
or uniqueclass
names to have to match up against each other, your HTML is more simplified, and you only have one event handler to set up.