Jquery Select all elements with data attribute common name [duplicate] - javascript

This question already has an answer here:
how do I find elements that contain a data-* attribute matching a prefix using jquery
(1 answer)
Closed 9 years ago.
I'm trying to use jQuery to select all the inputs in my form that have a data attribute with a similar name.
This is my form:
<form id = "myForm">
<input name="name" data-valid-presence=true >
<input name="age" data-valid-biggerThan="18" >
<input name="email[0]" data-valid-email=true >
<input name="email[1]" data-valid-email=true >
</form>
and my jQuery selector is:
var inputs = jQuery("#myForm").find("input[data-valid-email],[data-valid-length],[data-valid-presence], [data-valid-biggerThan]");
I'm looking for a way to select all the inputs that have a data-valid-* in them without having to find them one by one like this.
Any ideas?

You can use jQuery.filter:
var inputs = $('form').find('input').filter(function() {
var matched = false;
$.each(this.attributes, function(attr) {
if ( matched ) return;
matched = /^data-valid/.test(this.name);
});
return matched;
});

Related

How to select inputs of type file that have been loaded by the user? [duplicate]

This question already has answers here:
How do I select elements on multiple attribute values
(6 answers)
Closed 3 years ago.
Assuming you have a large number of inputs of type 'file', like so:
<input type="file" id="fileSomething1" />
<input type="file" id="fileSomething2" />
Is it possible to select all inputs of type 'file' that the user has loaded at least 1 file into?
I tried this, but it didn't work:
$("input[type='file' && value!='']").length
You have incorrect syntax for chaining of multiple attribute equals selector. It should be:
$("input[type='file'][value!='']").length
Working Demo
I would also suggest you to consider using .filter() selector for comparing value condition.
This code enable loop checking for input type file,If any of it find having value then it would print
$("#butn").on("click", function() {
$("input[type=file").each(function() {
if ($(this).val() != "") {
console.log($(this).attr('id'))
}
});
})
$("input[type=file").on("change", function() {
if ($(this).val() != "") {
console.log($(this).attr('id'))
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="fileSomething1" />
<input type="file" id="fileSomething2" />
<button id="butn">click</button>

How to get previous DOM element in Javascript? [duplicate]

This question already has answers here:
Get next / previous element using JavaScript?
(10 answers)
Closed 6 years ago.
I'm using javascript to access previous element's attribute value.
My HTML :
<form>
<div>
<label for="name">Name :</label>
<input type="text" name="name">
</div>
<div>
<label for="email">E-Mail :</label>
<input type="email" name="email">
</div>
</form>
I use loop to read all input elements in my form.
But, i want to read the label's HTML.
ex.
Input Element : 'email'
Label : 'E-Mail'
Also i want Javascript Solution ONLY !
//////// I'm not using jQuery ! ///////
You can use .previousElementSibling property to get the label element.
var el = document.getElementsByTagName('input');
for(var i =0; i< el.length;i++){
console.log(el[i]);
console.log(el[i].previousElementSibling);
if(el[i].getAttribute("name")==el[i].previousElementSibling.getAttribute("for")){
console.log("it is label");
}
}
Here is the jsfiddle example.
Used the code here:Find html label associated with a given input
//associate all labels to inputs:
var labels = document.getElementsByTagName('LABEL'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor != '') { var elem = document.getElementsByName(labels[i].htmlFor)[0]; if (elem) elem.label = labels[i]; } }
//get email for example
email=document.getElementsByName("email")[0];
EmailLabelvalue=email.label.innerHTML;
It connects every label with its Input, than you can easily get it using input.label. To get its containing value use .innerHTML ...

Jquery selector for all elements with class in a form that are after one element [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I need to find all elements with class 'complexList' in form that are after 'el'.
Example
var el = $(this);
var els = $('#' + obj.tableId + '_editorForm').find('.complexList');
el.nextAll('.complexList') //dont work
Thanks
If nextAll doesn't work, it means there are elements at various levels of nesting. But you can still do it, with index and slice.
els = els.slice(els.index(el) + 1);
index, when called as above, finds the index of the given element in the matched set; slice returns a subset of elements from a set. So we ask for the subset starting with the element after el.
Example:
var obj = {
tableId: "foo"
};
$(document.body).on("click", ".complexList", function() {
var el = $(this);
var els = $('#' + obj.tableId + '_editorForm').find('.complexList');
els.css("color", ""); // clear previous
els = els.slice(els.index(el) + 1);
els.css("color", "blue");
});
All of the text fields below are `.complexList` fields. Click any of them to turn all `.complexList` elements <em>after</em> it blue.
<form id="foo_editorForm">
<label>
Field 1:
<input type="text" class="complexList" value="field1">
</label>
<label>
Field 2:
<input type="text" class="complexList" value="field2">
</label>
<label>
Field 3:
<input type="text" class="complexList" value="field3">
</label>
<label>
Field 4:
<input type="text" class="complexList" value="field4">
</label>
<label>
Field 5:
<input type="text" class="complexList" value="field4">
</label>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JS: name of last input element (HTML/PHP) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I better make a list in order to explain the steps that I would like to do:
Get the name of the last element of the html-input (has been generated via PHP)
The basic setting looks like this:
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
Pass it over to a JS function
Append some additional fields (use part of the name as an id for new fields
The JS-script works fine and I am able to add fields. Also the content of the fields is being processed by the PHP script and written in a db.
Short: how do I get the last value, no matter how many fields there are?
edit: I had forgotten that there is a submit button that would appear as the last element as well ... sorry for that
There are a number of approaches, but given all other answers rely on the jQuery library (which adds an unnecessary overhead), I'll focus on showing some plain JavaScript approaches (works on recents browsers above IE8+).
var allTextInputs = document.querySelectorAll('input[type="text"]'),
lastInput = allTextInputs[allTextInputs.length - 1],
lastInputName = lastInput.name;
var allInputsTxt = document.querySelectorAll('input[type="text"]');
var lastInput = allInputsTxt[allInputsTxt.length - 1];
var lastInputName = lastInput.name;
var lastInputValue = lastInput.value;
alert('last input name : ' + lastInputName + '; last input value : ' + lastInputValue);
<input type='text'name='E_8' value= '123' />
<input type='text'name='E_9' value= '456' />
<input type='text'name='E_10' value= '789' />
<input type='submit' name='submit' value='Update'/>
If what you want is the value and not the name attribute, do this after using the same approach as above to get the name of the last <input type="text"/>:
var lastInputValue = lastInput.value;
These approaches will give the value of the last <input /> of the type="text" in the document at the point at which the code is run; to find the value of a last <input /> that's dynamically added to the document, you'll need to re-run a working approach following that element's insertion.
jQuery...
var lastInputName = $('input[type="text"]:last').attr('name');
The following jQuery code should do the trick.
var lastValue = $("input[type=text]:last").val();
Also with jQuery:
var $inputs = $("input[type=text]");
var lastValue = $inputs[$inputs.length - 1].value;
Use CSS3 selectors in combination with sizzle (jquery) to target last element
var name = $('input[name^=E_]:last')[0].name
the last value in PHP or JavaScript?
in PHP the fields are normally passed as an array, so you can get the last value using
end($array)
Even better if you name your filed like this
<input type='text'name='E[8]' value= '123' />
<input type='text'name='E[9]' value= '456' />
<input type='text'name='E[10]' value= '789' />
in JS you need to get the fields into an array and get the last.... you need something like this
var myFields = document.forms["myform"].getElementsByTagName('input'),
var lastValue = myFields[(myFields.length-1)].value;
By wrapping your code a parent element, let's says with an attribute id="inputs", here is a vanilla DOM (no jQuery) solution :
// start by finding the last-most element
var lastInput = document.getElementById('inputs').lastElementChild;
// search backward to the last 'text' element
while (lastInput && lastInput.type !== 'text') {
lastInput = lastInput.previousElementSibling;
}
// and get its value
var lastValue = lastInput ? lastInput.value : null;
The interesting part of this solution is that is create no array, so you save some JavaScript memory.
It should be ok with Firefox, Chrome and IE 9.

How do I use JavaScript to display one value in multiple places marked by elements with the same class? [duplicate]

This question already has answers here:
What is wrong with this getElementsByClassName call in Javascript? [duplicate]
(4 answers)
Closed 9 years ago.
I am trying to show the same text value in designated elements marked by the same class. Basically, this text is a value that I am getting from a form input tag. I am trying to do this with JavaScript using a getElementById to gather the text value and then getElementsByClassName to replace the text value in specified places of a page. Please see the following code first in HTML:
collective noun: <input type="text" id="noun1" onkeypress="runGather()"><br>
something the <i class="collective_noun">collective noun</i> can make: <input type="text" id="noun2"><br>
adj describing <i class="collective_noun">collective noun</i>: <input type="text" id="adj"><br>
and then in the JS file:
function runGather() {
var noun1 = document.getElementById("noun1").value;
var collective_noun = document.getElementsByClassName("collective_noun").value;
for (var i = 0; i < noun1.length; i++) {
collective_noun[i].innerHTML = noun1;
}
}
You're setting collective_noun to just a value when you want to use the nodelist that's returned, and you're trying to loop through noun1, which is just the value of the node. Try this instead:
var i, l,
noun_1,
collective_nouns;
noun_1 = document.getElementById('noun_1').value;
collective_nouns = document.getElementsByClassName('collective_noun');
for (i = 0, l = collective_nouns.length; i < l; i += 1) {
collective_nouns[i].innerHtml = noun1;
}
Instead of using plain JavaScript, you could save yourself the headache and use jQuery. Here's a one-line example using jQuery:
$(".collective_noun").text( $("#noun1").val() );

Categories