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.
Related
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()
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 few div elements where within each div tag, I have other form elements. For eg:
<div id="div1"><input type="text" name="answer" id="answer"></div>
<div id="div2"><textarea name="answer" id="answer">Some Value</textarea></div>
<div id="div3"><textarea name="answer" id="answer">Some Value</textarea></div>
How can I retrieve the textarea for div3 only. Here is what I have, but I am always only getting back the text area of div2
var divElement = dojo.byId('div3');
if ($('textarea', divElement).length > 0){
var text = $('textarea#answer').val();
}
Help!
var firstTextarea = $('#div3').find('textarea :first').val();
Try the following selector
var value = $('#div3 textarea').val();
alert(value);
Note: Your solution is using duplicate id values for the textarea and input tags. It's not legal to have multiple id`s and will lead you to pain down the road. It would be best to change your tags to have unique id's and then query that directly. For example
HTML:
<div id="div1"><input type="text" name="answer" id="answer1"></div>
<div id="div2"><textarea name="answer" id="answer2">Some Value</textarea></div>
<div id="div3"><textarea name="answer" id="answer3">Some Value</textarea></div>
Javascript
var value = $('#answer3').val();
alert(value);
well, you have assigned same ids to 3 elements, that is not a good practice. Every element should have unique id. In case you have assigned same id, you will always retrieve first element from your code.
If you want to retrieve div 3 textarea, use following selector :
$('#div3 textarea).val()
Short Question:
How do you link a label element to an input element without using the input element's id using jQuery and javascript?
Long Question:
I am using jQuery to clone a form with possibly more than one instance of the form being available for the user to fill in.
A label's 'for' attribute is supposed to be set to the 'id' attribute of the input element that it is for. This works when the input element has a unique id.
Because I am cloning the same input element there will be multiple input elements with the same id in the document. Therefore I'm avoiding having id attributes for input elements but I'd still like to focus on the input element when the label is clicked. I also want to avoid generating random ids for fields or setting onclick events on labels.
Edit #1
Example mark up (note no ids)
<form>
<label>First Name:</label><input type='text' name='FirstName' /><br/>
<label>Last Name:</label><input type='text' name='LastName' /><br/>
</form>
Example cloning code:
var newForm = $('form').clone();
$(newForm).find('label').each(function(){
var inputElement = $(this).next('input');
// I'd love to set the label's for attribute to an element
$(this).attr('for', inputElement);
});
$(document).append(newForm);
Edit #2
There currently are three options:
Set onclick events for labels to focus on the input field they're for. Criteria for deciding which labels are for which inputs can be the next input element or something else
Embed the input fields in the label fields (might not be possible due to designer's choices)
Generate random ids while cloning each form
Well it would be nice to see the markup, but if i can assume that the markup will look somewhat like this
<form name="f1">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
<form name="f2">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
then you could do something like this
$('form label').live('click',function(){
$(this).next('input').focus();
});
you will need to use live or delegate since you're cloning the forms on the fly i'm assuming.
The simplest solution is to move the <input> tags inside the <label> tags and forgo the for attribute altogether. Per the HTML spec, <input> tags without for attributes are implicitly associated with their contents.
Try this:
<form>
<label>First Name: <input type='text' name='FirstName' /></label><br/>
<label>Last Name: <input type='text' name='LastName' /></label><br/>
</form>
(See: http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1)
You shouldn't have multiple identical ids in the page. It defeats the purpose of the id attribute and is against the W3C spec.
Regardless, jQuery's $(this) could help you in this situation. Say you gave all your the "focusable" class. Then you could do:
$('.focusable').focus( function(){
$(this).doSomething();
});
This is really an HTML question. A label can be associated wtih a form control either by its for attribute having the same value as the associated control's id attribute, or by having the control as a child of the label, e.g.
<form ...>
<label for="nameField">Name:<input id="nameField" name="nameField" ... ></label>
<label>email:<input name="emailField" ... ></label>
</form>
I suppose in jQuery you need something like:
var labelAndInput = $('<label>text<input ... ></label>');
or whatever. Note that older versions of IE (and maybe more recent ones too) the label will not be associated with the control without the for attribute (or htmlFor property), there is no other way.
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.