My problem is, I want to retrieve checkbox id at runtime and use them later for other purpose.
But retrieved id is read as object.
My Code is:
// Following code gives id of checkbox which contains myCheckbox as its id.
var myCheckbox= $('input[id$=myCheckbox]')[0].id;
// and Now I want to check if that checkbox is checked with following code:
if ($(myCheckbox).is(':checked'))
return 1;
else
return 0;
But here myCheckbox id is read as Object instead of id and thus always enter in else condition and returns 0. This code works when I enter id of checkbox directly.
if ($('#ctl001_myCheckbox').is(':checked'))
return 1;
else
return 0;
It shouldnot be so complicated, I have been working with Javascript but new to JQuery.
You are getting the ID correctly, but the jQuery selector requires the # symbol, much in the same way as a CSS selector does. You need to add the # character to your selector:
if ($('#'+myCheckbox).is(':checked'))
return 1;
else
return 0;
BenM is correct, but why are you getting the ID of the element, and then look it up again? You already found the element, there is no need to search for it a second time.
Just keep a reference to the element:
var myCheckbox = $('input[id$=myCheckbox]').first();
// or var myCheckbox = $('input[id$=myCheckbox]')[0];
// and later
if (myCheckbox.is(':checked')) {
// or if (myCheckbox.checked) {
Simply:
return (($('#' + myCheckbox).is(':checked')) ^ false);
Have you tried using:
var myCheckbox= $('input[id$=myCheckbox]').attr('id');
Related
I'm currently struggling with my specific problem. I'm using Symfony Collection entity type and https://symfony-collection.fuz.org/symfony3/ bundle for front-end render. When I click to add a new collection, the new set of input is rendered. I need to hide a specific inputs when a condition is not met. To do that I'm using jQuery. At the start I declare an array of possible HTML ids.
var regularityWeeksArray = [
'#user_working_hours_weeks_0_regularity', '#user_working_hours_weeks_1_regularity',
'#user_working_hours_weeks_2_regularity', '#user_working_hours_weeks_3_regularity'
]
Then I join it for jQuery's requirements, because I didnt figured out how to workaround that. I would love to use this code to run that, but I need to get which specific element of an array is being changed to give my function ID of the element. Now I'm changing the first one, because I don't know how to meet my requirements.
var regularityWeeksArrayToString = regularityWeeksArray.join(', ');
$(document).on('change', regularityWeeksArrayToString, function() {
if($(this).val() === 'interim'){
showInterimWithID(0);
} else {
hideInterimWithID(0);
}
});
Do you have any ideas how to do this? Thanks a lot in advance, I'm really losing my hair for couple of hours now.
//EDIT: for context, this is how showsInterimWithID() looks like, it shows specific inputs and its labels.
function showInterimWithID(id){
$('#user_working_hours_weeks_'+ id +'_interim_from, label[for=user_working_hours_weeks_'+ id +'_interim_from]').show();
$('#user_working_hours_weeks_'+ id +'_interim_to, label[for=user_working_hours_weeks_'+ id +'_interim_to]').show();
}
this.id is the ID of the target of the event. You can get its index in the array.
$(document).on('change', regularityWeeksArrayToString, function() {
var index = regularityWeeksArray.indexOf(this.id);
if($(this).val() === 'interim'){
showInterimWithID(index);
} else {
hideInterimWithID(index);
}
});
I am working on a javascript code where I can clone an element, but also want to delete one on click. Cloning works, but I can't remove one.
I have the following elements.
<input list="accountsdeb" name="deblist[1]" id="deblist" autocomplete="off">
<input list="accountsdeb" name="deblist[2]" id="deblist" autocomplete="off">
And now I want to remove the last one on click (last = highest number).
function remove1() {
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
var elem = document.getElementsByName("deblist["+dbla+"]");
alert(dbla);
//var last = debelelast - 1;
elem.parentNode.removeChild(elem);
}
As an orientation I used to have a look on an example from W3S and Stack. I have also seen that this works:
var elem = document.getElementById("myDiv");
elem.parentNode.removeChild(elem);
But this is random and as you can see I have tried to include this in my code.
The error I get is:
Uncaught TypeError: Cannot read property 'removeChild' of undefined
at HTMLAnchorElement.remove1 (index.php:179)
Where's the problem in my code, where is my thinking wrong?
I see two issues in the piece of code you provided,
deblist is used as id for 2 elements which is not advisable and due to this document.querySelectorAll('#deblist').length returns 2 (I am not sure if you intending to do so)
document.getElementsByName() (check here) will return a NodeList which needs to be iterated in order to access any of the returned elements. So here you need to select the child element by giving its index. In your case elem will have one element for the matched name deblist[2] and hence you need to access it like elem[0] for selecting its parent and deleting its child.
So the updated the code would be,
var dbl = document.querySelectorAll('#deblist').length;
var dbla = dbl;
// console.log('dbla', dbla);
var elem = document.getElementsByName("deblist["+dbla+"]");
// console.log('elem 0', elem[0]);
// console.log('elem parentNode', elem[0].parentNode);
//var last = debelelast - 1;
elem[0].parentNode.removeChild(elem[0]);
Check the fiddle here
If the inputs are part of a group they could share a name property or such, and the use of jQuery could help you do something like...
$("input[name='group1']").last().parent().remove()
Or if not part of a group then just....
$("input").last().parent().remove()
I need to change the href of link in a box. I can only use native javaScript. Somehow I have problems traversing through the elements in order to match the correct <a> tag.
Since all the a tags inside this container are identical except for their href value, I need to use this value to get a match.
So far I have tried with this:
var box = document.getElementsByClassName('ic-Login-confirmation__content');
var terms = box.querySelectorAll('a');
if (typeof(box) != 'undefined' && box != null) {
for (var i = 0; i < terms.length; i++) {
if (terms[i].href.toLowerCase() == 'http://www.myweb.net/2/') {
terms[i].setAttribute('href', 'http://newlink.com');
}
}
}
However, I keep getting "Uncaught TypeError: box.querySelectorAll is not a function". What do I need to do in order to make this work?
Jsfiddle here.
The beauty of querySelectorAll is you dont need to traverse like that - just use
var terms = document.querySelectorAll('.ic-Login-confirmation__content a');
And then iterate those. Updated fiddle: https://jsfiddle.net/4y6k8g4g/2/
In fact, this whole thing can be much simpler
var terms = document.querySelectorAll('.ic-Login-confirmation__content a[href="http://www.myweb.net/2/"]');
if(terms.length){
terms[0].setAttribute('href', 'http://newlink.com');
}
Live example: https://jsfiddle.net/4y6k8g4g/4/
Try This:
var box = document.getElementsByClassName('ic-Login-confirmation__content')[0];
Since you are using getElementsByClassName ,it will return an array of elements.
The getElementsByClassName method returns returns a collection of all elements in the document with the specified class name, as a NodeList object.
You need to specify it as follows for this instance:
document.getElementsByClassName('ic-Login-confirmation__content')[0]
This will ensure that you are accessing the correct node in your HTML. If you console.log the box variable in your example you will see an array returned.
you can select by href attr with querySelector,
try this:
document.querySelector('a[href="http://www.myweb.net/2/"]')
instead of defining the exact href attribute you can simplify it even more :
document.querySelector('a[href?="myweb.net/2/"]'
matches only elments with href attribute that end with "myweb.net/2/"
Please I have my Jquery code that I want to do few things since. I have a form with a bunch of textboxes. I want to validate each textbox to allow numbers only. To also display error where not number.
var validateForm = function(frm){
var isValid = true;
resetError();
$(":text").each(function(variable){
console.log("The variable is" , variable);
if(!isNormalInteger(variable.val))
{
$("#error"+variable.id).text("Please enter an integer value");
isValid = false;
}
});
if(!isValid)
return false;
};
The above fails. When I print the variable on my console I was getting numbers 0 - 9. My textboxes where empty yet, it returns numbers. I tried variable.val() still fails and return numbers. I modified my select to
$("input[type=text]", frm).each();
Where my form is my form selected by id. It also failed. Below is the example of my html label and textbox. I have about ten of them
<div class="grid-grid-8">
<input class=" text" id="id" name="name" type="text">
<br>
<p class="hint">Once this limit is reached, you may no longer deposit.</p>
<p class="errorfield" id="errorMAXCASHBAL"></p>
Please how do I select them properly? Moreover, my reset function above also returns incrementing integers for value. The p property is of class errorField and I want to set the text property. Please how do I achieve this? Previously I tried the class name only $(.errorField). It also failed. Any help would be appreciated.
var resetError = function(){
//reset error to empty
$("p errorfield").each(function(value){
console.log("the val", value);
//value.text() = '';
});
};
//filter non integer/numbers
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
The main problem is your selectors in javascript. And as laszlokiss88 stated wrong usage of .each() function.
Here is a working example of your code: jsFiddle in this example all .each() functions use $(this) selector inside instead of index and value
You are using .each wrong because the first parameter is the index and the second is the element. Check the documentation.
Moreover, the correct selector for the resetError is: p.errorfield
So, you should modify your code to look something like this:
var resetError = function(){
$("p.errorfield").each(function (idx, element) {
$(element).text("");
});
};
With this, I believe you can fix the upper function as well. ;)
I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
You're using document.getElementById, but form elements have a name.
Try f.elements.namedItem("exclusions") instead of exclusions != null
Multiple elements in the same page cannot share an id attribute (ie. id must be unique or unset). As well, though some (older) browsers erroneously collect elements whose name matches the ID being looked for with getElementById, this is invalid and will not work cross-browser.
If you want to get a group of elements, you can give them all the same name attribute, and use document.getElementsByName to get the group. Note that the result of that will be a NodeList which is kind of like an array in that it can be iterated over.
Do all the checkboxes have the same id == exclusions?
If yes, then you must first correct that.
Before you do so, did you try checking the first checkbox and see if the if condition goes through?
if you have more than one element with the id "exclusions" it will screw up the functionality of getElementById. I would remove the duplicate "exclusions" ids from all of your elements and use getElementByName() instead, and give your group of checkboxes the name="exclusions" instead.
Edit:
But there is a much simpler way using jQuery, and it gives you some cross browser compability guarrantee. To do the same thing with jQuery do this:
var checkBoxesExist = $('[name=exclusions]').count() > 0;
Or if you have given your elements unique ID's then you can do this:
var checkbox1exists = $('#checkBox1').count() > 0;
Each element must have a unique ID.
Then, you can check just like this:
if (document.getElementById('exclusions1')) {
//field exists
}
Or if you need to loop through a bunch of them:
for (x=0; x<10; x++) {
if (document.getElementById('exclusions' + x)) {
//field X exists
}
}