creating an element and setting its attribute with jQuery - javascript

I'm trying to create an <ol> element with jQuery and set its class and id attributes. Is there any way to do this all at once? None of my ideas have worked so far, I'm still very new to jQuery...

There are at least a couple of different ways to do this:
$('<input id="something" class="something-else" type="text" />')
.appendTo('#someSelector');
or
$('<input type="text" />').attr('id','something')
.addClass('something-else')
.appendTo('#someSelector');

Related

Is there a way in JQuery to find if a sibling of an input has a given css class?

<span>
<input name="" autocomplete="off" label="" class="form-control mandatory field-mandatory" placeholder="">
<span class="goog-combobox-button"/>
<input type="hidden" value="3" id="ctl00_cntMainBody_OBJECT_ONE__PMLookupField" name="ctl00_cntMainBody_OBJECT_ONE__PMLookupField">
</span>
I would like to find out if there is a way, using jQuery, to find if the input above the one with id=ctl00_cntMainBody_OBJECT_ONE__PMLookupField has a css class field-mandatory. There are many spans on the page with similar to this one. I am working within the existing structure of html with no option to change. Since the input has no id the only way to locate it is by using the input below it that has an id.
Find each hidden input and target the sibling you want :-
$("input[type='hidden']").each(function() {
var inputAbove = $(this).siblings('input.field-mandatory');
// DO SOMETHING
});

How can I use setAttribute on an input without an ID or class attribute?

I have a search input tag that is being added by a jQuery plug-in:
<input type="search" />
Note that this does not have an ID, CLASS, or NAME. I need the search input tag to look like this:
<input type="search" name="myname" />
A simple solution is for me to update the jQuery plug-in. However, I do not want to do this as it will cause challenges when I upgrade this plug-in in the future.
This JavaScript works properly and adds the name attribute:
$(document).ready(function() {
document.getElementsByTagName("input")[0].setAttribute("name", "myname");
});
The problem is that the "[0]" in this function relies on the search input being the first input field in the form. I do not think this solution is sustainable.
There are other inputs in the form. This is the only one with the type attribute equal to "search." Is there a way to identify it by this attribute? Or, is there another solution you propose?
Thank you for your time!
You can use the document.querySelector:
document.querySelector("input[type='search']")
Below is an example (you can inspect the output to see name attribute):
document.querySelector("input[type=search]").setAttribute("name", "myname");
<input type="search" value="foo" />
<input type="bar" value="bar" />
You can target a selection by anything. So, the selector input[type="search"]' will work.
If you want to apply this to all input's of type search, this is good enough, and you get all of them in here:
$('input[type="search"]')
This works without jQuery too:
document.querySelectorAll('input[type="search"]')
A more targeted approach would be
document.querySelectorAll('div.filter input[type="search"]')

Complex CSS selector - how to require visible

I'm writing a CSS selector, which I have working so far:
input[placeholder*='mail']
but I'd like to ensure it's not finding invisible (ie: not visible) elements.
I've been trying :visible in various places in the pattern (because I couldn't find a good reference on the CSS selector lexer, but not luck with these:
input[placeholder:visible*='mail']
input:visible[placeholder*='mail']
input[placeholder*='mail']:visible
How do I do this? And anyone have a good reference on learning more complex selector formats?
:visible is a jQuery selector. Not a CSS one.
And you can't use it on an element's attribute like placeholder.
To check if there is an inputted value (which makes the placeholder "not visible"), you need to use some client-side code.
The jQuery would look like this:
$("input[placeholder*='mail']").each(function(){
if( $(this).val() != "" ){
// Do something.
// ...
}
});
To "filter out invisible elements" and keep only the visible ones:
var visible = $("input[placeholder*='mail']:visible").length;
console.log(visible+" elements are visible.");
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="one" placeholder="My mail">
<input type="text" id="two" placeholder="Your mail">
<input type="text" id="three" class="hidden" placeholder="Junk mail">
<input type="hidden" id="four" placeholder="Cool mail">
There is no CSS selector for :visible. You sould then work with classes and target the elements which have the class .visible. (Or NOT have the class .visible.
The :visible selector is only available in jQuery for example, which uses the pseudo selector for finding elements visible in current scroll view.
You can't do it with only CSS.
But you can do it with jquery and most probably this answer can help you.

Javascript get values of multiple text fields

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'm having trouble traversing a newly appended DOM element with jQuery

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.

Categories