I am new to javascript and I am trying to change the state of check boxes by checking for their id in get query string values. For example, if we have the following url http://localhost/aasd/index.php?category[]=74, I want to change the checkbox with id 74 to be checked.
I am trying to do it with the code below but it's not working
$(document).ready(function() {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
document.getElementById(pair[1]).checked = true;
}
pair[1] produces undefined74 I cant change check box state with that. I need to pass 74 to document.getElementById(pair[1]).checked = true;for the check box to be checked.
Any help would be appreciated
try this.. did it with an assumptions that url will have only one parameter.
$(document).ready(function() {
var url = window.location.href;
document.getElementById(url.substr(url.indexOf('=') + 1)).checked = true;
});
Check out this code:
$(document).ready(function() {
qsArray = new Array();
var query = "http://localhost/aasd/index.php?category[]=74";
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
$("#"+pair[1]).attr("checked",true); // this will make the checkbox checked when it encounters check box with id 74 I have created a check box with id 74 in my jsfiddle
}
});
Link to fiddle: https://jsfiddle.net/d5wbo91m/2/
Related
Hello I'm trying to add a class to all of my elements on a webpage. The overall goal is to grab all the elements on a webpage and add in a class. The class containing a font size will be changed to hide a message.
I'm getting this error
Uncaught TypeError: Cannot set property 'innerHTML' of null
I've tried moving my script outside the body tag of my index.html but its still not working.
Another problem is I can't add a class to all of the IDs I'm selecting. I can add classes manually like
$("#iconLog").addClass("style"); //this works
but when I try to add a class like this
empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
I'll post my entire script below for reference
$(function() {
var hideMsg = "f";
var n = hideMsg.length;
var i;
var j;
var holder;
var hideHolder;
// on button click - hide msg
$('#btnHide').on('click', function() {
//grab all IDS ON WEBPAGE
var allElements = document.getElementsByTagName("*");
var allIds = [];
for (var i = 0, n = allElements.length; i < n; ++i) {
var el = allElements[i];
if (el.id) {
allIds.push(el.id);
}
}
//ERRORS HAPPENING IN THIS LOOP
for(var i = 0; i < allElements.length; ++i)
{
console.log(allIds[i]);
try{
var temp = document.getElementById(allIds[i]).id;
}
catch(err){
document.getElementById("*").innerHTML = err.message;
}
tempTwo = "#" + temp;
console.log(tempTwo);
//$("#iconLog").addClass("style") //this works
$("tempTwo").addClass("style"); //this does not work
}
for(i = 0; i < n; i++) {
//set var holder to first value of the message to hide
holder = hideMsg.charCodeAt(i);
for(j = 7; -1 < j; j--) {
//set hideHolder to holders value
hideHolder = holder;
//mask hideHolder to grab the first bit to hide
hideHolder = hideHolder & (1<<j);
//grab the first element ID
if(hideHolder === 0) {
// embed the bit
// bitwise &=
} else {
//embed the bit
// bitwise ^=
}
}
}
});
});
To add a class to all elements you don't need a for loop. Try this:
$("*").addClass("style");
Same for setting the inner html of all elements. Try this:
$("*").html("Html here");
Remove the double quotes from empTwo .You don't need quotes when you are passing a varible as a selector. The variable itself contains a string so you don't need the quotes.
empTwo = "#" + temp;
$(empTwo).addClass("style") //this will work
Try this:
$(empTwo).addClass("style")
Note: You used string instead of variable:
well,
try this...
You were passing the varibale in the quotos because of that instead of getting value to empTwo it was searching directly for "empTwo".
$(empTwo).addClass("style");
to get all element try this-
var allElements = = document.body.getElementsByTagName("*");
Hoping this will help you :)
empTwo = "#" + temp; //where empTwo is a string that equals "#iconLog"
$("empTwo").addClass("style") //this does not work
You made mistake in the second Line.
The variable empTwo already is in string format.
So all you need to do is
$(empTwo).addClass("style") //this works because empTwo returns "#iconLog"
I want to make some refinement to some code from a previous question:
// the new base url
var base = ' https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var links = document.getElementsByTagName('a');
for(var i = 0;i < links.length;i++){
// check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec(links[i].getAttribute('href'));
if(result){
// make a new url using the 'base' and the 'asin' value
links[i].setAttribute('href', base+result[1]);
}
}
Now, instead of it acting on all links, can I get it to only look at links that are from images?
Here is an HTML snippet to show what I mean:
<img width="125" height="125" border="0" src="http://ecx.images-amazon.com/images/I/01W9a7gwosL.jpg" alt="43453">
That's an image link - I do want it to act on that.
Impossible?
My gut instinct is that this isn't actually possible in code - because document.getElementsByTagName('a') can't see the difference between a text link and an image link.
Use querySelectorAll to pre-select only the right kinds of nodes. EG:
// the new base url
var base = 'https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var linkImgs = document.querySelectorAll ("a > img");
for (var J = linkImgs.length - 1; J >= 0; --J) {
var imgLink = linkImgs[J].parentNode;
//--- Check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec (imgLink.getAttribute ('href') );
if( result) {
// make a new url using the 'base' and the 'asin' value
imgLink.setAttribute ('href', base+result[1]);
}
}
You could use regex to check for the link inside the HTML of the link:
for(var i = 0;i < links.length;i++) {
// check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec(links[i].getAttribute('href'));
// check each link for an img tag
var hasimage = /<img [^>]+>/.test(links[i].innerHTML);
if(result && hasimage){
// make a new url using the 'base' and the 'asin' value
links[i].setAttribute('href', base+result[1]);
}
}
Also, using regular expressions to search for HTML probably isn't the best bet, but if you control what's being generated, then this is probably the quickest way without a 3rd party html parser.
You can filter the links based on whether or not they contain an image.
var links = document.getElementsByTagName('a');
links = [].filter.call(links, function(item) {
// test to see if child node is an image
return item.childNodes[0].nodeName === 'IMG';
});
for(var i = 0;i < links.length;i++){
// do what you gotta do
}
You can just test for an IMG child and only process the link if there is one there.
Example on JSFiddle
// the new base url
var base = ' https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var links = document.getElementsByTagName('a');
for(var i = 0;i < links.length;i++){
var linkElement = links[i];
//get the first child of the a element
var firstChild = linkElement.children[0];
//if there is a child and it's an IMG then process this link
if (typeof(firstChild) !== "undefined" && firstChild.tagName=="IMG") {
// check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec(links[i].getAttribute('href'));
if(result){
// make a new url using the 'base' and the 'asin' value
links[i].setAttribute('href', base+result[1]);
}}
}
// the new base url
var base = ' https://www.example.co.uk/gp/wine/order?ie=UTF8&asin=';
var links = document.getElementsByTagName('img');
var hrefs = links.parent;
for(var i = 0;i < hrefs.length;i++){
// check each link for the 'asin' value
var result = /asin=([\d\w]+)/.exec(hrefs[i].getAttribute('href'));
if(result){
// make a new url using the 'base' and the 'asin' value
hrefs[i].setAttribute('href', base+result[1]);
}
}
There is a links collection, and you can can just check if the link has an image child node:
var link, links = document.links;
var re = /asin=([\d\w]+)/;
for (var i=0, iLen=links.length; i<iLen; i++) {
link = links[i]
if (link.getElementsByTagName('img').length && re.test(link.href)) {
link.href = base + result[1];
}
}
My initial response would be to look into query Select All and then assign a class name to grab on all of the a tags that would be affected by whatever your trying to do. When I get to my laptop I'll edit this with an example.
I have a contact form that I'm going to validate with JS.
I want a function to loop through all the inputs and work out which one is the email by searching it for a '#' symbol, then assigning it to a variable to be handled later.
I've initialized variables for each input box and assigned them as values in the input array.
I've looped through them and checked them against a regular expression (a simple a-z letter check), just to make sure they've all had content inputted.
If they match the RegExp then I want them to be passed to a string search to look for an # symbol to determine which one is the email input.
This is my code below but it's not working.
Can anyone tell me where i've gone wrong?
Thanks!
var emailaddress;
function find_email() {
var name = document.getElementById("username");
var email = document.getElementById("email");
var msg = document.getElementById("messagecontent");
var racenum = document.getElementById("racenum");
var input = [name, email, racenum, msg];
for (i = 0; i <= input.length; i++) {
var standard_check = /[a-zA-Z0-9]/g;
if (input[i].value.match(standard_check)) {
var str = input[i].value;
str.search("#");
if (str.match("#")) {
emailaddress= str;
}
}
}
}
The Problem with this code is that you have for (i = 0; i <= input.length; i++) which attempts to go one pass the number of elements in the array. Get rid of the equals making it for (i = 0; i < input.length; i++) and you should be fine.
Do you have to do anything special while passing in a dynamically created string as a clientID for document.getElementById?
I have a asp:gridview control that has a textbox column and a checkbox column. I added an onclick event to the checkboxes to set the textbox value of that row to the max value of all checked rows +1. I pass in the IDs of the grid and the controls of the row that was selected. I can getElementByID fine for these controls, but When I dynamically build the IDs of the other controls, I keep getting null, even though I know that the IDs are correct. My code is bellow.
function SetPriority(cbID, tbID, gridID) {
var cb = document.getElementById(cbID);
if (cb.checked) {
var tb = document.getElementById(tbID);
var grid = document.getElementById(gridID);
var maxv = 0;
for (var i = 0; i < grid.rows.length; i++) {
var indexID = 102 + i;
var cbClientID = 'LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ct' + indexID + '_chkGroup';
var tbClientID = 'LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ct' + indexID + '_txtPriority';
console.log("row" + i);
//just for example of how it should be working
console.log(cbID);
var cbx = document.getElementById(cbID);
console.log(cbx);
//get row checkbox
console.log(cbClientID);
var thisCB = document.getElementById(cbClientID);
console.log(thisCB);
//get row textbox
var thisTB = document.getElementById(tbClientID);
console.log(thisTB);
if (thisCB) {
if (thisCB.type == "checkbox") {
if (thisCB.checked) {
if (thisTB.value > maxv)
maxv = thisTB.value;
}
}
}
}
tb.value = parseInt(maxv) + 1;
}
}
Here is how its showing up in the console, where you can see the IDs for the first row are the same
For Those wondering about How I am calling the function, I am adding it on to a checkbox in a .net gridview control on row databind. It renders as follows:
<input id="LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_chkGroup" type="checkbox" name="LeaveInfo$pnlMain$wgbLeaveSummary$gridSubmitted$ctl02$chkGroup" onclick="javascript:SetPriority('LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_chkGroup','LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted_ctl02_txtPriority','LeaveInfo_pnlMain_wgbLeaveSummary_gridSubmitted');">
The vb .net code to add the function is this...(on-_RowDataBound)
Dim chk As CheckBox = CType(e.Row.FindControl("chkGroup"), CheckBox)
Dim tb As TextBox = CType(e.Row.FindControl("txtPriority"), TextBox)
chk.Attributes.Add("onclick", String.Format("javascript:SetPriority('{0}','{1}','{2}');", chk.ClientID, tb.ClientID, gridSubmitted.ClientID))
No, you don't have to do anything special when dynamically building a string. A string in javascript is the same string whether it was built dynamically or specified directly in your code. If document.getElementById() is not working, then one of the following is likely the cause:
Your string isn't what you think it is so it doesn't match the target id.
Your DOM id isn't what you think it is.
You have multiple elements with the same id (not likely here because you won't get null)
You are calling getElementById() before the DOM is ready or before the desired elements have been added to the DOM.
In this case, it seems more likely that 1) or 2) are the issues here, but you don't show us any context to know whether 4) could be the problem.
Not 100% sure, but I think it could be a context issue. Try this:
function ( id ) {
var ID = document.getElementById;
this.id = id;
this.newvar = ID.call( document, this.id );
...
}
Also, this question may help you — it has a good explanation on context and assigning a var to getElementById Why can't I directly assign document.getElementById to a different function?
I couldnt figure out why my IDs that seemed identical were not. I will leave this question open for anyone to add insight on how to remedy this. I ended up just getting my elements by cell and not by ID.
function SetPriority(cbID, tbID, gridID) {
var cb = document.getElementById(cbID);
if (cb.checked) {
var tb = document.getElementById(tbID);
var grid = document.getElementById(gridID);
var maxv = 0;
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
var thisCB = grid.rows[row].cells[5].childNodes[1];
if (thisCB == cb) {
continue;
}
var thisTB = grid.rows[row].cells[6].childNodes[1];
if (thisCB.type == "checkbox") {
if (thisCB.checked) {
if (thisTB.value > maxv)
maxv = thisTB.value;
}
}
}
}
tb.value = parseInt(maxv) + 1;
}
}
I am having checkbox in each itemTemplate of asp:gridview
I want to get ids or values of those many selected checkboxes using only javascript
In pure javascript I'm not sure about platform portability: you'd REALLY want jQuery or some other helper library here.
With jQuery:
var values = [];
var ids = [];
jQuery.each(jQuery("input:checkbox").find(":checked"), function(){
values.push(jQuery(this).val());
ids.push(jQuery(this).attr("id");
});
will give you the ids and values of all the checked checkboxes.
EDIT: ugly, but this might work...
var values = [];
var ids = [];
var inputs = document.getElementsByTagName("input");
var i;
for(i=0;i<inputs.length;i++){
if(inputs[i].hasAttributes() && inputs.getAttribute('type') == "checkbox" && inputs.getAttribute('checked')){
values.push(inputs[i].getAttribute('value'));
ids.push(inputs[i].getAttribute('id'));
}
}
Let me know if that does what you want.
I am not exactly sure on what you are trying to do but this might help you out. This will get all of the inputs on the screen and process only the checked ones.
var inputList = document.getElementsByTagName("input");
var resultsArray = [];
for(var i = 0; i < inputList.length; i++) {
if (inputList[i].getAttribute("checked") == true) {
resultsArray.push(inputList[i]);
}
}
Sorry, forgot to tell you that this would be a list of elements. You will then need to extract them however you want to from resultsArray.