I have 3 HTML form inputs fields that is dynamically generated by a "add more" button, with naming for the fields name as fieldName, fieldName1, fieldName2, fieldName3, and so on.
Now, I'm trying to retrieve the value from this fields with JavaScript, using the script below.
var bookingForm = document.forms['formName'];
var qty = bookingForm.fieldName +'i'.value;
with the 'i' been a generated numeric number by a for loop
when I use alert(qty), it returns NaN, when I'm expecting the value for fieldName1, fieldName2, and so on.
But when I use;
var qty = bookingForm.fieldName.value
I can get the value in that field but get NaN when I try to concatenate 1,2,3, with the fieldName.
Any help will be very much appreciated.
You use brackets to access a property using a string:
var qty = bookingForm['fieldName' + i].value;
You can't use code like:
var qty = bookingForm.fieldName +'i'.value;
bookingForm.fieldName +'i' is a string. You have to change that string into a DOM element in order to access the .value parameter.
Try document.getElementsByName('fieldName'+i)[0].value
Related
Consider that i have the following html
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="["Pool","Office","Sprinkler","Boiler"]">
To fetch the values i use
a = $('#other_floor_plans').val()
It returns the following
"["Pool","Office","Sprinkler","Boiler"]"
If i use a[0], it returns "[" as output. I need to get "Pool" as the first value.
How to accomplish this?
Your value is a type of string which has a correct JSON syntax. Just parse with JSON.parse into the array and use your syntax.
const value = '["Pool","Office","Sprinkler","Boiler"]';
const array = JSON.parse(value);
console.log(array[0]);
I think you need to change little bit of your code specially in markup.
changed your input markup into this <input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
then get value by jQuery
var a = $('#other_floor_plans').val(),
a = JSON.parse(a);
console.log(a[0]);
you need to use JSON.parse because you get json formate value and need to be parsed.
for my recommendation you just comma separate value like
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value="Pool, Office, Sprinkler, Boiler">
then get first value by jQuery
var a = $('#other_floor_plans').val().split(",");
console.log(a[0]);
This one is much more readable and easy I guess.
You can use eval function to convert string to array and get the value.
var a = "['Pool','Office','Sprinkler','Boiler']"; // or you can also assign like this var a ='["Pool","Office","Sprinkler","Boiler"]'
var firstItem = eval(a)[0];
console.log(firstItem); //output will be "Pool"
There you doing a wrong practice when you initialize value in input box you must contain a value in different quotation symbols.
there you take " for value assign and " also for array string, that truncate your string on the second " that's why this return only [ in your value.
Try to use like this:
HTML
<input type="text" id="other_floor_plans" name="other_floor_plans[]" value='["Pool","Office","Sprinkler","Boiler"]'>
JQuery
var a = $('#other_floor_plans').val();
a = JSON.parse(a);
console.log(a);
I have value that is displayed in span tag. If i want to post the value i have to assign that value to an input. So this is the code i have written to assign value to input and trying to post that value. But when i alert the assigned value its
showing as
[object Object]
Pls check the code and correct me.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);
and i tried this also
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);
Both the above code shows
[object Object]
Because of this i am not able to post values.
That is because the value setter function on an input return the jQuery object of that input element only, it allows you to chain the event.
Try this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Read more about it here http://api.jquery.com/val/#val-value
"lower" is an object. if you want to see the text inside, you need to call lower.val().
e.g.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
jQuery supports chaining objects return.
So, whenever you do an operation on an object (except some like .val() getter, it returns object of that selector element.
So, you can do much more operations in a single statement.
In your statement,
var lower=$("#inputElement").val(value);
alert(lower);,
It is returning the object of element #lower.
You can add more operations to it.
For example:
var lower=$("#inputElement").val(value).css('color', 'red');
You want only plain value.
So, rather you should do this:
var value = $("#spanElement").text();
$("#inputElement").val(value);
var lower=$("#inputElement").val();
alert(lower);
Just do in this way..
var span_text = $("#spanElement").text(); //get span text
$("#inputElement").val(span_text); //set span text to input value
var input_value = $("#inputElement").val(); //get input value
alert(input_value); //alert input value
Hope this will help
This is because it will return a jQuery object . If you want to see the same text which is in the input you can either use .val() like answered previously or use like this
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert($("#spanElement").prop('innerHTML'));
WORKING DEMO
You are getting 'Object Object' because lower is an object if you want to get the text you need to perform below actions.
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Or
var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());
Hope it helps !
Hi I have an array like this.
var i;
for(i=0;i<10;i++){
$('<input/>').attr('type','text')
.attr('name','TxtBx_[]')
.attr('id','TxtBx_' + i)
.attr("readonly","readonly")
.attr('value',i)
.addClass('txtbx')
.appendTo($div);
}
And I prints the 10 input boxes well.
Later I need to get the number of text boxes I have created. So I'm using
var myarr=document.getElementsByName('TxtBx_');
var numberofElements=myarr.length;
but when I put an alert to check the value of numberofElements it gives me always 0. The length of the array must be 10. Could someone please let me know the mistake I have made.
The elements' names are TextBx[], not TxtBx_.
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Element names are TextBx[] and TxtBx_ is a class name
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Read getElementsByName() documentation for more information
var numberofElements = document.getElementsByName("TextBx[]").length;
Name of textbox is 'name','TxtBx_[]' getting by TxtBx_.
Because no element has name TxtBx_ . It's TextBx[] actually.
Since you are alrady using jQuery, you can find by class like below,
$('.txtbx').length
Few other things, I would like to add here.
attr accepts a object too. So, you can pass all inputs at once. Also, you can pass attributes as second arguement while dynamically creating input. Also, according to jQuery docs, you should specify type in input type while dynamically creating them or it won't work in some IE.
So, try something like this,
var i;
for(i=0;i<10;i++) {
$('<input type="text"/>',{
'name': 'TxtBx_[]',
'id': 'TxtBx_' + i,
'readonly':'readonly'
'value': i,
'class': 'txtbx'
}).appendTo($div);
}
Try it
$("input.txtbx").length;
Just use the class to get them:
var numberofElements = $('.txtbx').length;
<script type="text/javascript">
$(document).ready(function() {
var sub_total = $("sub_total").text();
alert(sub_total);
var ship_total = $("ship_total").val()
alert(ship_total);
var new_total = sub_total + ship_total;
$('#new_total').html( new_total.toFixed(2));
});
</script>
I'm using alert to test the output and It is not getting the value inside the span ID.
$<span id="sub_total"><?php echo $sub_total = number_format($this->cart->total(), 2); ?></span></td>
This does display correctly on the page but the alert is a blank box. Causing the new_total value to stat NaN not a number.
How do I add the values in these two fields?
EDIT:
You forgot to get the value - you are only getting the element
Since you're already using jQuery you can get the value like
var sub_total = parseInt($("#sub_total").text());// this is where you need to use .text()
var ship_total = parseInt($("#ship_total").text());
or if you want to keep plain js..
document.getElementById("sub_total").value
Since you have $ in your text you need to get rid of it before parsing it. You can use regex as #Bubbles stated or whatever method you want to remove the $ sign.. ex. substring.. split..
$.trim($("#sub_total").text().split('$')[1])
or
$.trim($("#sub_total").text()).substring(1)
wirey gives a good review of part of the problem, but as is I don't believe it's enough. "parseInt" won't work on "$20", you have to remove the dollar sign first. If you're feeling lazy, this is nothing a good regex won't be able to solve in short order:
var sub_total = parseInt($("#sub_total").text().match(/[0-9]+/)));
var ship_total = parseInt($("#ship_total").text().match(/[0-9]+/)));
This will just grab the number from the span, then parse it.
I have a textbox and need to send the value of the text box when you type some number and the radio button is checked, to a jquery function. The code I'm using now is:
var radiobuttoncustom = 0;
if (document.getElementById('radiobuttoncustom').checked) {
radiobuttoncustom = document.getElementsByName("some_number").value;
}
I will then display the results using "radiobuttoncustom" but when the results is displayed it is NaN instead of the number. Right now I'm using the textboxes name to get the value.
getElementsByName returns an HTMLCollection, not an element, which would not have a value attribute.
Have you tried:
radiobuttoncustom = document.getElementsByName("some_number")[0].value;
edit: if you are dealing with numbers, you should also parse them as such:
radiobuttoncustom = parseInt(document.getElementsByName("some_number")[0].value, 10);
Since you are using jquery, why not
$('input[name=some_number]').val();
and
if($('#radiobuttoncustom').prop("checked"))