jQuery .insertAfter only once with a class selector - javascript

I have the following code that is working correctly to insert a success span after an input field when a correct value is entered. But my problem is that it adds the span every time I leave the field. From question Jquery insertAfter only once if element exist I know that I could set the ID of the span when created and check the length each time the event fires to see if it already exists. But am not sure how to do that when using a class to select the fields.
Any help with class selectors would be helpful.
$(".systemFieldName").blur(function(){
var val = $(this).val();
var exists = $.inArray(val,allFields);
if (val!="" && exists>=0){
$("<span class='label label-success'>Valid</span>").insertAfter(this).one();
}
});

This should help.
allFields=["121",'test'];
$(".systemFieldName").blur(function(){
var val = $(this).val();
var exists = $.inArray(val,allFields);
//See if the next element is a span with class label.
var nextEl=$(this).next(); //next element
var add=true; //add by default
if(nextEl.hasClass('label-success')) add=false; //don't add.
if (val!="" && exists>=0 && add){ //only insert if all conditions are true.
$("<span class='label label-success'>Valid</span>").insertAfter(this).one();
}else if((val == "" || exists < 0) && !add) { // The !add means there is already the Valid span, we can safely remove nextEl, if the value changes.
nextEl.remove();
}
});
https://jsfiddle.net/ym66f48p/2/
This checks to make sure the next element is a span, it also includes a remove function that if the value is altered later on, it will remove the valid span, but ONLY if the next element is already a valid span.
use 121 or test as your testing in the jsFiddle.

Try this fiddle: https://jsfiddle.net/8jpc74z8/
All I am doing here is to check whether there is any sibling to the systemFieldName already added. If not, then add.
if($(".systemFieldName +.label-success").length === 0){

Related

Check if Element is last element in Selection

How can I check if the current element in a .each loop is the last element in a selection?
I have tried it with the following code:
$('#order').find('.xyz').find('input[id ^="order"]').not('[id $="_zyx"]').each(function (index, element) {
var isLast = ($(element) == $('#order').find('.xyz').find('input[id ^="order"]').not('[id $="_zyx"]').last());
});
With the query I am getting three elements. And I want to select the last element of this selection for further use.
In order to determine which element is the right one I have tested it with the code above but I am getting false for isLast for the last element where it should be true.
Am I missing something?
You don't need to use Jquery for this.
Use the length of your elements and the index of your loop.
var elements = $('#order').find('.xyz').find('input[id ^="order"]').not('[id $="_zyx"]');
elements.each(function (index, element) {
var isLast = (index+1) === elements.length;
});
It would be helpful to see your HTML, but you should just be able to use the last selector:
https://api.jquery.com/last-selector/

jQuery - append string to input when changed

I have multiple select inputs on a page and I'd like to set all of them to have a particular option selected if a checkbox is checked
Once the form is submitted the inputs that have been updated will be looped through and sent to the database, so I have a function to append a string to the option value which is called on change of the select
This is all working great, however I'd like to append the updated string (to the value, not text) when the select option is changed by the checkbox being checked, but can't seem to get this to work
Fiddle https://jsfiddle.net/69zzr6xa/2/
I've tried looping through each select like so and then checking if the second option is already selected. If not, append the string, but it doesn't appear to work
$('select').each(function() {
if (!$(this).$('option').text == 'Two') {
var inputname = $(this).find(":selected")[0].value;
$(this).(":selected").val(inputname + "-updated");
}
});
I think this is what you are looking for.
function set_to_two() {
$('option:nth-child(2)').each(function(){
$(this).prop('selected', true);
if( $(this).val().indexOf('-updated') < 0 ){
$(this).val( $(this).val() + "-updated" );
}
});
set_updated();
}

How to append Span to input field dynamically using native javascript

I have 5 input box in my page. I want to check if any field is blank, i will show the error message using a span tag appending to that input field.
Here is my code:
function validateForm() {
// Declare all the local variable
var inputElements, inputId, inputType, i, inputLength, inputNode;
// Get all the input tags
inputElements = document.getElementsByTagName("input");
for(i = 0, inputLength = inputElements.length; i < inputLength; i++) {
inputId = inputElements[i].id; // Get the input field ID
inputType = inputElements[i].type; // Get the input field type
// We will ONLY look for input[type=text]
if(inputType === "text") {
inputNode = document.getElementById(inputId);
if(inputNode.value === "") {
var spanTag = document.createElement("span");
spanTag.innerHTML = inputFieldBlankErrorMessage;
console.log(inputNode.appendChild(spanTag));
}
}
}
return false; // Do Nothing
}
This is what i am getting
It should append after the input tag. I am getting a weird tag which i don't need. Please help!!!
You can't .appendChild() anything to an input node, since an input can have no descendants.
Instead, you should insert the new node after it, or something similar.
inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);
DEMO: http://jsfiddle.net/hMBHT/
Simply put you are not supposed to append any elements to input elements.
What you probably want is something like this:
<div class="field">
<input type="text" name="bla"/>
<span class="error">This field can't be blank!</span>
</div>
So you need to insert the span before or after the input element.
Here is an answer that shows you how.
I believe that your issue is that you are trying to append the span as a child of the input, not a sibling (which, I believe, is what you really want).
I can't to be sure without seeing your actual HTML, because I don't know how your inputs are situated in the DOM, but if they have separate parent elements, then you would replace:
inputNode.appendChild(spanTag);
. . . with
inputNode.parentNode.appendChild(spanTag);
Edit: FYI, the code that squint gave below (inputNode.parentNode.insertBefore(spanTag, inputNode.nextSibling);) would be how you could do it if all of the inputs are under the same parent element. It all depends on how the DOM structure is set up.

jQuery/javascript - list box item deselect/show/hide not working in IE?

I have the following javascript/jquery code, the purpose of which is to -
Deselect a previously selected item from the list, if the selected item value exists in an array
Hide/display each list item dependent on whether they exist in the array
var list = $(row).find("select > option")
var selectedValue = $(row).find("select > option:selected")
if (selectedValue) {
if ($.inArray(selectedValue[0].value, dependencyListItemValues) == -1) {
alert('deselect');
$(selectedValue).attr("selected", false);
}
}
$(list).each(function () {
var value = this.value;
if (value != "") {
if ($.inArray(value, dependencyListItemValues) > -1) {
alert('show');
$(this).show();
}
else {
alert('hide');
$(this).hide();
}
}
});
This is working fine in chrome and firefox, but not in IE9. When running in IE, the alert lines are hit, but the following lines seemingly do nothing:
$(selectedValue).attr("selected", false);
$(this).show();
$(this).hide();
Do I need to use alternative code so this will work in IE?
First: You can use
list.each
instead of $(list).each.
Second, you cannot hide an OPTION element in crossbrowser way.
So, you must remove it (for hide) and re-create it (for show).
You can store all options (and them parent) in array, like so:
var cache_options= [];
list.each(function(index) {
cache_options.push({el:$(this), parent:$(this).parent()});
});
and after
for(var i = 0; i<cache_options.length; i++) {
var value = cache_options[i].el[0].value;
if (value != "") {
if ($.inArray(value, dependencyListItemValues) > -1) {
cache_options[i].parent.append(cache_options[i].el);
}
else {
cache_options[i].el.remove();
}
}
}
Tested!
OK my solution was as follows ... this is based on the answer by meder (thanks!) on this question - Hide select option in IE using jQuery
Firstly, in place of this line:
$(selectedValue).attr("selected", false);
I did this:
$(row).find("select")[0].selectedIndex = -1;
And to show/hide the relevant list items, I had to first wrap those that I needed to hide in a span and then apply the .hide() command, and for those I needed to display, replace the span with the original option element:
//first we need to hide the visible list values that are not in the list of dependent list values.
//get the list values which are currently displayed, these will be the 'option' elements of the 'select' element (list).
//the hidden values are within a span so will not be picked up by this selector
var displayedListValues = $(row).find("select > option")
//loop through the displayed list values
$(displayedListValues).each(function () {
//get the value from this 'option' element
var displayedValue = this.value;
//ignore empty values (first blank line in list)
if (displayedValue != "") {
//if the value is not in the list of dependent list values, wrap in span and apply .hide() command
if ($.inArray(displayedValue, dependencyListItemValues) == -1) {
$(this).wrap('<span>').hide();
}
}
});
//now we need to display the hidden list values that are in the list of dependent list values.
//get the list values which are currently hidden, these will be the 'span' elements of the 'select' element (list).
//the visible values are within an 'option' so will not be picked up by this selector
var hiddenListValues = $(row).find("select > span")
//loop through the hidden list values
$(hiddenListValues).each(function () {
//find the 'option' element from this 'span' element and get its value
var opt = $(this).find('option');
var hiddenValue = opt[0].value;
//ignore empty values (first blank line in list)
if (hiddenValue != "") {
//if the value is in the list of dependent list values, apply .show() command on the 'option' element
//(not sure why the .show() command works in this case?)
//and then replace the 'span' element with the 'option' element, which is effectively removing the span wrapper
if ($.inArray(hiddenValue, dependencyListItemValues) > -1) {
$(opt).show();
$(this).replaceWith(opt);
}
}
});
Which works fine ... although rather annoying I had to do this rather messy re-coding just because IE doesn't support .show() and .hide() of list values!!!!!
Here is a good solution:
http://ajax911.com/hide-option-elements-jquery/

find ID of previous button

I'm looking to find the id of the previous button. It is pretty far away - lots of table rows, tables, divs, etc. between the target and the button but I thought this would still work:
alert( $(this).prevAll("input[type=button]").attr('id') );
Unfortunately this returns alerts 'undefined'. Help?
function getPrevInput(elem){
var i = 0,
inputs = document.getElementsByTagName('input'),
ret = 'Not found';
while(inputs[i] !== elem || i >= inputs.length){
if(inputs[i].type === 'button'){
ret = inputs[i];
}
i++;
}
return (typeof ret === 'string') ? ret : ret.id;
}
That probably isn't the most efficient solution, but it's the only one I can think of. What it does is goes through all the input elements and finds the one right before the one you passed into the function. You can use it like this, assuming you're calling it correctly and this is the input element:
getPrevInput(this);
Demo
That kind of lookup might be expensive. What about doing a select for all your input[type=button] elements, and traversing that array until you find the element matching your id. Then you can simply reference the array index - 1 to get your answer.
Is the previous button a sibling of the current button? If not, prevAll() won't work. The description of prevAll():
Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.
Depending on your DOM structure, you can use a combination of parents() and then followed by find().
This function looks up all input[type=button] elements and uses the jQuery index function to find your current element in this group.
If it could be found and there is a previous element it is returned.
$.fn.previousElem = function(lookup){
var $elements = $(lookup),
index = $elements.index(this);
if(index > 0){
return $elements.eq(index-1)
}else{
return this;
}
}
HTML:
<div><div><div><div>
<input type=button id=1 value=1 />
</div></div></div></div>
<div><div><div><div>
<input type=button id=2 value=2 />
</div></div></div></div>
JS:
alert ($("#2").previousElem('input[type=button]').attr('id'))
http://jsfiddle.net/SnScQ/1/
Here's a different version of Amaan's code, but jqueryfied and his solution wasn't looking for a button. The key to the solution is that jQuery returns the elements in document order, as do document.getElementsByTagName and similar functions.
var button = $('#c');
var prevNode;
$("input[type=button]").each(function() {
if (this == button[0]) {
return false;
}
prevNode = this;
});
alert(prevNode && prevNode.getAttribute('id'));
http://jsfiddle.net/crFy6/
have you tried .closest? ...
alert( $(this).closest("input[type=button]").attr('id') );

Categories