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.
Related
Is it possible to find out an element ID in the same sentence?
<div class="test">
<input id="999" type="text" data-test="2">
</div>
Example
$('.test').find('[data-test="2"] #999)
I tried to find a specific input in my html code, but this input exists many times with the same id value, the only difference is the attr "data-test" (the number is incremental)
Any help for this?
So here is an example, problem is 999 is not valid for an ID, and will not work in a query selector.
Remember an id should be unique also, so I am not sure why you need to combine?
const parent = document.querySelector('.test');
const child1 = parent.querySelector('[data-test="2"]');
const child2 = parent.querySelector('[data-test="3"]');
console.log(child1.value);
console.log(child2.value);
<div class="test">
<input class="demo1" type="text" data-test="2" value="input1">
<input class="demo1" type="text" data-test="3" value="input2">
</div>
If your markup is valid, ids need to be unique for the entire page. So you can skip the data part of the selector.
$('#999')
Will do the trick in a valid document. However if you use incremental numbers for various elements your ids are likely not unique. It would be better to use classes in this case.
I need to find a certain class and then find an input which is nested a number of elements below it. I need the target classes name as to append it.
I thought i could use .queryselector but it seems not. I cannot use the ID on the input.
var input = document.querySelectorAll('.pt-page.pt-subpage-current input');
var solve = input[0];
console.log(solve);
<div class="pt-page pt-subpage-current"> /*only identifier*/
<div class="container">
<div class="question">
<div class="input">
<input name="school" type="text" id="schoolCode1" autocomplete="off">/*target*/
</div>
</div>
</div>
</div>
I thought i could use query selector like above (I have been through many iterations) but no dice.
Use the direct descendant selector >
$('#mainDiv > p:first')
or even children()
$('#mainDiv').children('p').first()
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";
I want to getElementById of a certain form but it displays the error
Uncaught TypeError: Object # has no method 'getElementById'
here is my code
varForm = document.forms['newform'].getElementById("yellow");
an ID is unique -
so there is no difference (you get what you want), calling it directly(/correctly):
var Form = document.getElementById("yellow");
As others have pointed out, as far as Id is unique we have getElementById in document:
varForm = document.getElementById("yellow");
But if you still insist on finding a node based on a specific dom node, you can try:
varForm = document.forms['newform'].querySelector("#yellow");
Use following way to get input values from another form e.g.
Forms
<form id="form1">
<input id="txt1" type="text" value="111"/>
</form>
<form id="form2">
<input id="txt1" type="text" value="222"/>
</form>
Js
//get input value from current form i.e. form 1
alert(document.getElementById("txt1").value) //111
//get input value from other form i.e. form2
alert(document.forms["form2"].txt1.value) //222
Unlike some other element-lookup methods such as
Document.querySelector() and Document.querySelectorAll(),
getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM.
Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.
So Keep in Your mind about this method:
it is called on the document object
it returns a single item
var Form = document.getElementById("yellow");
this will get your form.
Consider this form:
<form id="myform"><input id="lala" type="text" value="123"/></form>
There are several ways to get the value of the "lala" input:
console.log(document.getElementById("lala").value)
console.log(document.forms[0].lala.value)
console.log(document.forms["myform"].lala.value)
console.log(document.forms.myform.lala.value)
Here is the Fiddle to play with.
Ok, I am trying to create myself a reusable function that I can have ultimately return an object of all form elements in a given container such as a div, or a specific form. However I seem to be stuck with passing the actual container/form to my function so it can run over the elements.
currently I have:
function findAllFormElements(formElem)
{
//detect all form elemets on the page in a given form/container
formObj = {};
$(formElem ':input').each(function(key, val)
{
$(document).append(val+'<br>');
});
console.log(formObj);
}
where formElem is expected to be the containing element/form element ie:
<div class="something">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<select>
<option></option>
</select>
<textarea></textarea>
</div>
or
<form class="something">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<select>
<option></option>
</select>
<textarea></textarea>
</form>
both would be acceptable container types in the long run as some forms in this project don't actually have form tags.
grant it my current example isn't exactly portraying what I want per say as it spits things out to the console, and appends them to the document but then end result once I get how I can pass the formElem parameter correctly so I can get all input types from straight <input> tags to <select>, textarea will be an object of all the form elements where there id/name is the key for the object and there value if any is the value. Either way just trying to figure out whats the best tactic for this type of capture. so I can iterate over the elements and get this information.
Using jQuery's .serializeArray() we can easily grab those <form> elements and create an object from them...
$('form').serializeArray(); // will turn into a key/value object
Since you want certain <div> collections to be serialized just do:
//turn that div (filled with inputs) into a form element
var tempForm = $('<form />', { html: $('#yourDiv').html() });
var objResult = tempForm.serializeArray(); // now serialize
jsFiddle Demo