hi everyone I have an element like this :
<div class="price-box">
<span class="regular-price" id="product-price-27">
<span class="price">
...
</span>
</span>
</div>
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />
i have tried to get the value using this line
document.getElementByClassName('input-text qty').value="myvalue"
but that didn't work
how can I get the value without jquery?
note : I've included prototype.js in my project !
what about this one too :
<button type="button" title="Add to Cart" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span>Add to Cart</span></span></button>
I want to disable it using Javascript and by its class name !!!?
You might be looking for querySelector:
document.querySelector( ".input-text.qty" );
This returns a single item, rather than a NodeList. If you would like a NodeList instead, use the alternative querySelectorAll. Keep in mind that these methods take CSS Selectors. The selectors you can use are limited to the browser this code is executed in. Keep it simple.
These two methods have better browser support than getElementsByClassName, so I would encourage you to use them instead of taking your current approach.
Demo:
Since you are using Prototype in the page already, you may find this element using the "double-dollar" method:
$$('.input-text.qty');
As others have pointed out above, this returns an array of matched elements (or an empty array, if you don't have anything on the page that matches). So the easiest way to do anything to the result is with invoke():
$$('.input-text.qty').invoke('setValue', 'myvalue');
or
$$('.input-text.qty').invoke('disable');
Any of the Prototype Element methods can be invoked in this manner. If you want to do something custom to the element(s) based on some attribute, you can use each() instead:
$$('.input-text.qty').each(function(elm){
if (elm.frobber == 'froom') elm.remove();
});
Firstly, its getElementsByClassName (elements is plural) -- this will return an array of elements that satisfy the condition. You must specify the index of the array to modify the element properties:
document.getElementsByClassName('input-text qty')[0].value="myvalue"
You have id="qty" so forget class, just use
document.getElementById('qty').value = "myvalue";
Which is most efficient.
Other dom native methods like getElementsByClassName/TagName(note there are s after Element) returns an array like object NodeList.
You need to use index or loop to access it.
You error is that you using:
1) getElementByClassName instead of getElementsByClassName
2) getElementsByClassName returns array so you must get [0] element
So try this one:
var p = document.getElementsByClassName('input-text qty')
console.log(p[0])
p[0].value = "MyValue"
Demo
getElementByClassName() returns the array of matched elements, so to acces the first element of array use 0 index like
document.getElementsByClassName('input-text qty')[0].value="myvalue";
Or
You can use the id(qty) from input tag, and put the value on this tag by getElementById() something like
<input type="text" name="qty" id="qty" maxlength="12" value="1" title="Qty" class="input-text qty" />
document.getElementById('qty').value="myvalue";
Related
Here is an example of my form (only inputs that I want, but there is many others):
<form name="inputform" action="..." method="post">
<input type="hidden" name="id_qtedje_77" id="id_qtedje_77" value="0">
<input type="text" id="id_qte_77" name="prestation_detail_fields[77][qte_collecte]" value="0.00">
<input type="text" id="id_rec_77" name="prestation_detail_fields[77][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_77" name="prestation_detail_fields[77][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[77][dechet_non_present]" value="1">
<!-- another TR -->
<input type="hidden" name="id_qtedje_108" id="id_qtedje_108" value="0">
<input type="text" id="id_qte_108" name="prestation_detail_fields[108][qte_collecte]" value="0.00">
<input type="text" id="id_rec_108" name="prestation_detail_fields[108][reliquat_conforme]" value="0.00">
<input type="text" id="id_ren_108" name="prestation_detail_fields[108][reliquat_non_conforme]" value="0.00">
<input type="checkbox" name="prestation_detail_fields[108][dechet_non_present]" value="1">
</form>
What I want is to get values of inputs, but as the form is built in PHP, I don't know the line identifier (77, 108).
Is there a way to do something like getElementByName('id_qtedje_%') ?
Note: I'm not using any library, and I don't plan to use one.
Your best bet is probably document.querySelectorAll, which you can use any CSS selector with, including an "attribute starts with" selector like input[id^="id_qtedje_"]. It's supported on all modern browsers, and also IE8:
var elements = document.querySelectorAll('input[id^="id_qtedje_"]');
If you wanted just the first match (rather than a list), you could use document.querySelector instead. It returns a reference to the first match in document order, or null if nothing matched.
Alternately, you could give the elements a class name, then use document.getElementsByClassName, but note that while getElementsByClassName was supported in old versions of Chrome and Firefox, IE8 doesn't have it, so it's not as well-supported as the more-useful querySelectorAll in the modern era.
var elements = document.getElementsByClassName("theClassName");
If you use any libraries (jQuery, MooTools, Closure, Prototype, etc.), they're likely to have a function you can use to look up elements by just about any CSS selector, filling the gaps in browser support with their own code. For instance, in jQuery, it's the $ (jQuery) function; in MooTools and Prototype, it's $$.
You can use the starts with selector in jQuery
var listOfElements = $('[name^="id_qtedje_"]')
You may also be interested with the contains and ends with selectors
Using querySelectorAll, you can do
document.querySelectorAll('[name^="id_qtedje_"]')
Alternatively:
Assuming that all elements are inputs, you may use this:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
return x[i];
}
}
}
which can be called as getElementByNameStart("id_qtedje_")
Note that this only returns the first element of this type. To return all:
function getElementByNameStart(str) {
var x=document.getElementsByTagName('input')
var a=[];
for(var i=0;i<x.length;i++) {
if(x[i].indexOf(str)==0) {
a.push(x[i])
}
}
return a;
}
If the elements are of any type, replace "input" with "*" (beware, this may make your code slow)
This seems like it should be simple but I can't get it to work. The environment I am working in requires that I use NAME instead of ID, so I am making certain that all of my names are unique. I simply want to get two numbers from input fields, add them together and put the answer into a read only field.
<input type="number" name="first_num"></input>
<input type="number" name="second_num"></input>
<input type="number" name="sum_of_num" readonly></input>
<button name="perform_sum" onclick="document.getelementsbyname("sum_of_num")[0].value=(document.getelementsbyname("first_num")[0].value+document.getelementsbyname("second_num")[0].value)">Sum</button>
<input type="number" name="first_num"></input>
<input type="number" name="second_num"></input>
<input type="number" name="sum_of_num" readonly></input>
<button name="perform_sum" onclick="document.getElementsByName('sum_of_num')[0].value = (parseInt(document.getElementsByName('first_num')[0].value) + parseInt(document.getElementsByName('second_num')[0].value))">Sum</button>
getelementsbyname -> getElementsByName (javascript is case sensitive)
" -> ' (if you use double apex in html you have to slash your double apex in javascript or have to use single apex in javascript, or reverse)
.value is string, you need to convert it in int
You'll need to use single quotes, otherwise it thinks the attribute is closed. Also the functions are case-sensitive so it should be getElementsByName
from
<button name="perform_sum" onclick="document.getelementsbyname("sum_of_num")[0].value=(document.getelementsbyname("first_num")[0].value+document.getelementsbyname("second_num")[0].value)">Sum</button>
to
<button name="perform_sum" onclick="document.getElementsByName('sum_of_num')[0].value=(document.getElementsByName('first_num')[0].value+document.getElementsByName('second_num')[0].value)">Sum</button>
jQuery answer because it's the easiest (even though you didn't tag jQuery):
$("button").click(function () {
var first_num = Number($("input[name='first_num']").val());
var second_num = Number($("input[name='second_num']").val());
$("input[name='sum_of_num']").val(first_num + second_num);
});
jQuery makes it super simple to select by attributes such as name.
you have to use parseInt function else it will just concat two box values.
I have a button and I want the click event to read the value of one of the preceding HTML elements. My HTML is
<div class="product_list_buy">
<div class="product_quantity">
<label for="qty">Qty:</label>
<input class="quantity" type="text" value="1">
</div>
<div class="addcart_wrapper">
<input class="product_id" type="hidden" value="5666" name="product_id">
<button class="btn-cart">
</div>
</div>
I am trying to read the value of quantity element by the following JQUERY:
jq('.storelist').unbind('click').on('click',".btn-cart",function(){
var product_qty = jq(this).closest("div").prev(".quantity").val();
.....});
But its not able to read the value of .quantity element. What am I doing wrong?
Consider using your classes from the highest object in the dom:
var product_qty = $(this).closest(".product_list_buy").find(".quantity").val();
http://jsfiddle.net/paska/bn7ag8j6/
var product_qty = $(this).closest("div").prev(".product_quantity").find(".quantity").val();
jQuery .prev (docs)
Given a jQuery object that represents a set of DOM elements, the .prev() method searches for the predecessor of each of these elements in the DOM tree and constructs a new jQuery object from the matching elements.
The method optionally accepts a selector expression of the same type
that can be passed to the $() function. If the selector is supplied,
the preceding element will be filtered by testing whether it match the
selector.
In your case, the predecessor of <div class="addcart_wrapper"> was <div class="product_quantity"> and you were using the selector ".quantity", so it didn't match, and returned an empty jQuery object.
What you should use is .prev(".product_quantity") to select <div class="product_quantity"> and then .find(".quantity") to select the input.
I have a dynamic web page where the content may contain between 1 and 10 links, provided in text boxes, similar to the following:
<input size="50" id="link" value="http://Something.Something" type="text">
<input size="50" id="link" value="http://SomethingElse.Something" type="text">
I need javascript to be able to read all of the links, and be able to manipulate the data (store in array, output to screen, etc)
I know that I can read a single id using the following
var link = document.getElementById('link');
Which will return the first match - but, how can I do a loop or obtain all the values for all the links, bearing in mind that the number of links cannot be determined beforehand?
P.S. I have tried using getElementsByTagName('input') but there are more inputs on the page, which means it's getting more results than I'd like it to get.
You can make them all have names and search by name.
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
Then you can get it with:
var vrows = document.getElementsByName("vrow");
alert(vrows.length);
Give them all a common class and access using document.getElementsByClassName('class').
IDs should be unique for each element. You could use document.getElementsByClassName or document.querySelectorAll(".class"); and then use the class name (assuming relatively modern browser). Or use document.getElementsByTagName() and then iterate through the elements comparing with the class.
Attach a jQuery lib and you will be able to do something like:
$('input[type=text]').each(function(i, val){
alert($(this).val());
});
I have a form that I want to be used to add entries. Once an entry is added, the original form should be reset to prepare it for the next entry, and the saved form should be duplicated prior to resetting and appended onto a div for 'storedEntries.' This much is working (for the most part), but Im having trouble accessing the newly created form... I need to change the value attribute of the submit button from 'add' to 'edit' so properly communicate what clicking that button should do. heres my form:
<div class="newTruck">
<form id="addNewTruck" class='updateschedule' action="javascript:sub(sTime.value, eTime.value, lat.value, lng.value, street.value);">
<b style="color:green;">Opening at: </b>
<input id="sTime" name="sTime" title="Opening time" value="Click to set opening time" class="datetimepicker"/>
<b style="color:red;">Closing at: </b>
<input id="eTime" name= "eTime" title="Closing time" value="Click to set closing time" class="datetimepicker"/>
<label for='street'>Address</label>
<input type='text' name='street' id='street' class='text' autocomplete='off'/>
<input id='submit' class='submit' style="cursor: pointer; cursor: hand;" type="submit" value='Add new stop'/>
<div id='suggests' class='auto_complete' style='display:none'></div>
<input type='hidden' name='lat' id='lat'/>
<input type='hidden' name='lng' id='lng'/>
</form>
</div>
ive tried using a hundred different selectors with jquery to no avail... heres my script as it stands:
function cloneAndClear(){
var id = name+now;
$j("#addNewTruck").clone(true).attr("id",id).appendTo(".scheduledTrucks");
$j('#'+id).filter('#submit').attr('value', 'Edit');
$j("#addNewTruck")[0].reset();
createPickers();
}
the element is properly cloned and inserted into the div, but i cant find a way to access this element... the third line in the script never works.
Another problem i am having is that the 'values' in the cloned form revert back to the value in the source of the html rather than what the user inputs.
advice on how to solve either of these issues is greatly appreciated!
I think you want to use find not filter
$j('#'+id).find('#submit')
That should work in practice, though you've got problems there because there are multiple elements with the same id. I'd change your HTML to use classes, or in this specific case, you don't need either:
$j('#' + id).find(":submit")
have you tried using .val()? and instead of .filter(), use .find()
$j('#'+id).find(':submit').val('Edit');
nickf solution works. (just wrote a piece of code to check that). Do check the definition of filter in jquery documentation.
Reduce the set of matched elements to those that match the selector or pass the function's test.
You have use find in this case. Also as nick mentioned having multiple elements with same id is troublesome, especially when you are doing dom manipulation. Better go with appropriate classes.