Jquery, ajax, javascript - getting an element by id - javascript

I have some ajax onclick stuff that updates this line when the value is selected from the menu:
<li id="li_273" data-pricefield="special" data-pricevalue="0" >
The intention is to take the that value (data-pricevalue) and then multiple it by the amount that is entered from another input box. Here's my function to try to make that happen:
$('#main_body').delegate('#element_240','keyup', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue");
var ordered = $(this).val();
var price_value = price * ordered;
price_value = parseFloat(price_value);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});
Except I get the following error:
Uncaught TypeError: Cannot call method 'data' of null
It appears as tho my attempt to get the price value out of getElementById isn't correct. Any suggestions?
UPDATE: The code above has been edited from your suggestions and thanks to all. It appears to be working just fine now.

This part is wrong:
var price = document.getElementById('#li_273').data("pricevalue").val();
Instead, you should use jQuery all the way here:
var price = $('#li_273').data("pricevalue");
Btw, you shouldn't use .val() because .data() already returns a string. .val() is used exclusively for input elements such as <input> and <select> to name a few.
Update
Also, the rest of your code should be something like this:
var price_value = parseFloat(price);
if(isNaN(price_value)){
price_value = 0;
}

getElementById doesn't return a jQuery object it returns just a normal DOM object.
You can wrap any DOM object in a jQuery call to get it as a jQuery object:
$(document.getElementById("li_273")).data("pricevalue").val();
Or better yet just use jQuery
$("#li_273").data("pricevalue").val()

Your call should be document.getElementById('li_273') it's a normal method and doesn't require the hash as jQuery does.
EDIT As #kennypu points out you're then using jQuery on a non jQuery object. #Craig has the best solution.

document.getElementById('#li_273').data("pricevalue").val(); should be jQuery('#li_273').data("pricevalue").val();
Again the variable price_value is not present, I think you mean price.
Ex:
$('#main_body').delegate('#element_240','keyup mouseout change', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue").val();
var ordered = $(this).val();
var price_value = parseFloat(price);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});

The document.getElementById('#li_273') is the problem. The method won't recognize the hash. If you want to get the element ID using that method try document.getElementById('li_273') and it will work.
Otherwise use all jQuery.

Since you're using jQuery, why are you using document.getElementById instead of $(...)? It should be:
$('#li_273').data("pricevalue")
Note also that the data() method is only defined on jQuery objects, not DOM elements. And you don't need to call val() after it -- that's for getting the value of form elements.

Your getElementById is wrong with javascript you do not need the #, if your using jQuery do it like this instead (Also I removed the .val() because its not needed):
$('#main_body').delegate('#element_240','keyup mouseout change', function(e){
var temp = $(this).attr("id").split('_');
var element_id = temp[1];
var price = $('#li_273').data("pricevalue");
var ordered = $(this).val();
price_value = parseFloat(price_value);
if(isNaN(price_value)){
price_value = 0;
}
$("#li_273").data("pricevalue",price_value);
calculate_total_payment();
});

Related

How to get value from text box by name which is dynamic

I need a value of text box for that I am using document.getElementsByName("elemntName") but the problem is the the name itself is dynamic, something like below.
for(temp = 0 ; temp < arracid.length ; temp++){
cell1=mynewrow.insertCell(4);
cell1.innerHTML="<input type='hidden' name='ACID"+index+"' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
index++;
}
When I tried var acidCount = document.getElementsByName('ACID') its not working and I tried
var acidCount = document.getElementsByName('ACID"+index+"') still not working
For every loop the name is changing like ACID1,ACID2 etc.. can anyone help me how to get the value of this text box?
Since you are already assigning an ID to your inputs, it's recommended to use getElementsById which is faster than getElementsByName (and more accurate because the IDs are supposed to be unique, while the names don't have to be). Try this:
var acidCount = document.getElementById("ACID" + index);
If you still want to use getElementsByName, try this:
var acidCount = document.getElementsByName("ACID" + index);
But remember that getElementsByName returns a list of elements, but the list has only one element, because your names are unique. If you want to get that element in the list, you can use it's index like this:
var acidCount = document.getElementsByName("ACID" + index)[0];
Alternatively, if you want to get the list of all your inputs, first remove the index from the name:
cell1.innerHTML="<input type='hidden' name='ACID' class='tblrows' id='ACID"+index+"' value='"+arracid[temp]+"'>";
Then use:
var acidCount = document.getElementsByName("ACID");
Note: all the above return the DOM element(s). If you're only interested in the value, use the value property:
var acidCount = document.getElementById("ACID" + index).value;
or
var acidCount = document.getElementsByName("ACID" + index)[0].value;
(This is a jquery solution, since the question was initially tagged with jQuery)
You can use the selector of input elements with name starting with ^= ACID:
$("input[name^=ACID]").each(function(){
console.log($(this).val());
});
Issue is with single quoutes and double quotes :
var acidCount = document.getElementsByName("ACID"+index)
Since there can be more than one element with same name, so we need to get first element with that name, I have corrected your query check this, it will work.
var acidCount = document.getElementsByName('ACID'+index)[0].value
Try using wildcard * in the selector which will return all matched elements
document.querySelectorAll('[id*=ACID]')
You can try using class name.
$(document).find(".tblrows").each(function(){
console.log($(this).val());
});
Since you are naming your elements 'ACID' + index, you can utilize the querySelector method as follows:
for (var i=0; i < arracid.length; i++) {
var $el = document.querySelector('#ACID' + i));
}

javascript - insert div after elements with a certain class on mouseover

I know that there is a really simple jQuery way to to this, but now I would like to understand why my code is not working properly:
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var menuHelp = document.querySelector(".menu_help");
for (var i = 0;i<menuHelp.length;i++){
menuHelp[i].onmouseenter = function(){
menuHelpPopup = document.createElement("div");
menuHelpPopup.setAttribute('class','menu_help_popup');
menuHelpPopup.innerHTML = "test";
insertAfter(menuHelp[i], menuHelpPopup);
}
menuHelp[i].onmouseleave = function(){
menuHelpPopup.remove();
}
}
What I'm trying to do is to create a popup and insert it after elements with a certain class when mouseover on them..
DEMO http://jsfiddle.net/r5e8rvkg/
Please make sure menuHelp is a nodeList, so you should use document.querySelectorAll;
When the mouse enter, the value of i is menuHelp.length. so you should use this, like insertAfter(this, menuHelpPopup)
I used getElementsByClassName and it seemed to have worked.
var menuHelp = document.getElementsByClassName('menu_help');
Please checkout here: http://jsfiddle.net/r5e8rvkg/1/
First, use querySelectorAll instead of querySelector.
More importantly, you need to take care that in your code:
menuHelp[i].onmouseenter = function(){
menuHelpPopup = document.createElement("div");
menuHelpPopup.setAttribute('class','menu_help_popup');
menuHelpPopup.innerHTML = "test";
insertAfter(menuHelp[i], menuHelpPopup);
}
The value i would not be passed in correctly because the event onmouseenter is Async. When the function is called, the value of i is actually i === menuHelp.length, which results in menuHelp[i] === undefined.
You need to use Closure, as shown in my JSFiddle code.
The document.querySelector() method returns only the first element with the specified selector. To get each element with class 'menu_help', you need to use the document.querySelectorAll() method.
In other words, replace:
var menuHelp = document.querySelector(".menu_help");
With
var menuHelp = document.querySelectorAll(".menu_help");

Show javascript array value in input type hidden

I have a question regarding Javascript array.
I have the following javascript array:
var startTimeList= new Array();
I've put some values in it. Now I have the following input (hidden type):
<input type="hidden" value"startTimeList[0]" name="startTime1" />
Hoewever, this is obviously not correct because the javascript array is not recognized in the input hidden type. So I cant even get one value.
Does anyone know how I can get a value in the input type from a javascript array?
You need to set the value in Javascript:
document.getElementById(...).value = startTimeList[0];
Use this :
<script>
window.onload = function() {
document.getElementsByName("startTime1")[0].value = startTimeList[0];
}
</script>
You have to set value from javascript.
Something like document.getElementById (ID).value = startTimeList[0];
You execute javascript from body oload event.
You need to set the value through JavaScript itself so.
document.getElementById("startTime1").value = startTimeList[0];
Or JQuery
$("#startTime1").val(startTimeList[0]);
Assign "startTime1" as the id above.
You can find your element by name with:
document.getElementsByName(name)[index].value = 'new value';
OR
You should identify your element and then change the value;
Give your element an ID for example id="ex"
Get the element with JavaScript(of course once the DOM is ready) with var element = document.getElementById('ex')
Change the value with element.value = 'your value';
You'd need to split the array into a delimited string and then assign that string to the value of the hidden input.
Then, on postback or similar events you'd want to parse the value back into an array for use in JavaScript:
var startTimeList = [1,2,3,4,5];
var splitList = '';
for(var i = 0; i < startTimeList.length; i++)
{
splitList += startTimeList[i] + '|';
}
and back again:
var splitList = '2|4|6|8|';
var startTimeList = splitList.split('|');

My javascript to jQuery translation has a bug

My guess is that this javascript just finds the div called divid and then uses it with the sendit function.
var somevalue = 19;
if (navigator.appName.indexOf("Microsoft") != -1) {
thediv = window["divid"];
} else {
thediv = document["divid"];
}
thediv.sendit(somevalue);
I would imagine in jQuery it would look something as simple as this:
var somevalue = 19;
$('divid').sendit(somevalue);
But it's not working!! What could I be missing?
I should say that it's in the middle of other javascript code, could that be a problem?
You would need to get the actual DOM object (not the JQuery collection) to access the function that you set on it.
$('divid').get(0).sendit(somevalue);
Assuming there is an element with ID 'divid' you need to use the ID selector #
var somevalue = 19;
$('#divid').sendit(somevalue);
That may not be the whole answer as it's unclear where sendit is defined.

Looping over elements in jQuery

I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though:
function config() {
$("#frmMain").children().map(function() {
var child = $("this");
if (child.is(":checkbox"))
this[child.attr("name")] = child.attr("checked");
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
return null;
});
Neither does the following (inspired by jobscry's answer):
function config() {
$("#frmMain").children().each(function() {
var child = $("this");
alert(child.length);
if (child.is(":checkbox")) {
this[child.attr("name")] = child.attr("checked");
}
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
});
}
The alert always shows that child.length == 0. Manually selecting the elements works:
>>> $("#frmMain").children()
Object length=42
>>> $("#frmMain").children().filter(":checkbox")
Object length=3
Any hints on how to do the loop correctly?
don't think you need quotations on this:
var child = $("this");
try:
var child = $(this);
jQuery has an excellent function for looping through a set of elements: .each()
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...
$("#formID").serialize()
It creates a string for you with all of the values automatically.
As for looping through objects, you can also do this.
$.each($("input, select, textarea"), function(i,v) {
var theTag = v.tagName;
var theElement = $(v);
var theValue = theElement.val();
});
I have used the following before:
var my_form = $('#form-id');
var data = {};
$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
function() {
var name = $(this).attr('name');
var val = $(this).val();
if (!data.hasOwnProperty(name)) {
data[name] = new Array;
}
data[name].push(val);
}
);
This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.
Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.
Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).
if you want to use the each function, it should look like this:
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
Just switch out the closing curly bracket for a close paren. Thanks for pointing it out, jobscry, you saved me some time.
for me all these didn't work. What worked for me was something really simple:
$("#formID input[type=text]").each(function() {
alert($(this).val());
});
This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.
EDIT
JSFIDDLE
The below will work
$('form[name=formName]').find('input, textarea, select').each(function() {
alert($(this).attr('name'));
});

Categories