JavaScript and URL parameters - javascript

I am using JQuery to push data to Google Analytics when the Ajax code is fired.
I need some help in capturing checkboxes with the same ID name. Basically, it's overwriting previous values with the last checkbox selected. Can someone help modify my code below to see if the checkbox is checked, and instead of overwriting, appending the value?
for (i = 0; i < arr.length; i++) {
// If the decode flag is present, URL decode the set
var item = decode ? decodeURIComponent(arr[i]) : arr[i];
var pair = item.split(spl);
var key = trim_(pair[0]);
var value = trim_(pair[1]);
if (key && value) {
obj[key] = value;
}
}
This is what part of my URL parameters looks like:
/ordersearch?soldToList=1001014377%7C1000%7CSP&shipToList=1001000903%7C1000%7CSH&startDate=03%2F22%2F2016&endDate=03%2F23%2F2016&orderStatus=Complete&
_orderStatus=on& orderStatus=Cancelled&
_orderStatus=on& orderStatus=Open&
_orderStatus=on& productStatus=COMPLETE&
_productStatus=on& productStatus=Cancelled&
_productStatus=on& productStatus=OPEN&
_productStatus=on& ponumber=8940324& materialnumber=98574395& ordernumber=7493278
Thank you.

Firstly I don't see any jQuery and thus I'm advising you to stick with dom selectors for this.
You can use document.getElementById('checkboxId').checked, which returns a boolean value, to see if the checkbox with checkboxId is checked.
Appending elements can be achieved like so; div.innerHTML = div.innerHTML + 'Extra stuff';
Your question and code combination are vague at best so I would recommend getting your logic right and only concentrating on syntax once you know exactly how you're going to achieve your goal.

Related

JavaScript - Find ID that matches data attribute value

I have a variable that finds the data attribute of an element that is clicked on in a callback function:
var dropdown = document.getElementsByClassName('js-dropdown');
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", callBack (dropdown[i]));
}
function callBack (i) {
return function () {
var thisDropdown = i.getAttribute('data-dropdown');
//rest of the code here
}
}
I am basically trying to do this
$('#' + thisDropdown ).toggleClass('is-active');
...but in vanilla JS.
This works fine using jQuery however I would like a vanilla version.
So when a user clicks on an element that activates a drop down, I want it to dynamically find its relevant ID matching value within the document so it can toggle a show/hide class.
I've searched through a lot of SO questions and everyone replies with a jQuery answer which is not what I am looking for.
I've been trying to do something along the lines of
var idValue = document.getElementById(thisDropdown);
Then
var findId= idValue + thisDropdown;
findId.toggleClass('is-active');
Obviously that does not work the same way the jQuery statement works... any ideas?
Ignore the toggleClass method! Some of you may find this contradictory as I want vanilla JS.
To replace $('#' + thisDropdown ).toggleClass('is-active'); with plain js, use Element.classList. Like this:
const someElement = document.querySelector('#' + thisDropdown);
someElement.classList.toggle("is-active");
I like #kamyl's answer, but you might need backward compatibility. For that, see if you can find a polyfill.
If you have to write it yourself, use string.split(" ") to get your list of active attributes and iterate to find if it exists; add if not, remove if so...then array.join(" ") and replace the class attribute with it.

javascript if statement syntax (need help)

I've looked through the prior questions but do not see an answer that I can understand (they are all more complicated than mine).
I'm bootstrapping some javascript using old manuals and my experiences using a scripting language back 15 years ago.
By modifying a tutorial file I have this code and it works fine
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
total_current_draw.value = oemdc1 + oemdc2 + oemdc3
But I need to add this code so that if the user clicks a radio button (include_prism_draw) they get a different total.
if (oemdc4 == 1)
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
else
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
But I get the added value (prism_cd) in my calculation regardless of the radio button values (a "1" or a "0"). Even if neither button is clicked I still get the added value.
So I think I need some braces or parentheses or something.
I have the var prism_cd declared at the top of the doc and it is inserted into a results field so it is working in that sense.
Any help is much appreciated.
(Okay, found the edit link, they should make it more prominent).
I cut/pasted the code from #Adam and still get the prism_cd regardless of the state of the buttons. (prism_cd is a number I set as a var and it shows up accurately but even when I don't want it.)
the button code is below. Maybe there is a simple mistake
Include PRISM 1.5 mA current draw in calculation?
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="1" /> Yes
<input type="radio" name="include_prism_draw" id="include_prism_draw" value="0" /> No
To answer the other question about the vars, they are from popups the user manipulates, the script adds the values from the popups and does so accurately until I add the yes/no code with the buttons.
If the user wants to add the prism current draw (prism_cd) they click yes and it is to be added but as I say it is getting added whenever the code is in the script. At this point I do not have either button set to be checked.
The rest of script works accurately as I can test with the spreadsheet I am porting it from.
I still have more things to work through but they are mostly based on this type of "if/else set a var" logic so once I get this working hopefully I should be good to go.
I very much appreciate the replies.
M./
I'm not certain what your problem is. But, the best practice for if..else syntax is to put both blocks in braces.
var oemdc1 = parseInt(document.getElementById("vehicle_oem_draw").value);
var oemdc2 = parseInt(document.getElementById("vehicle_added_draw").value);
var oemdc3 = parseInt(document.getElementById("new_vehicle_draw").value);
var oemdc4 = parseInt(document.getElementById("include_prism_draw").value);
var total_current_draw = document.getElementById("total_hourly_current_draw");
if (oemdc4 === 1){
total_current_draw.value = oemdc1 + oemdc2 + oemdc3 + prism_cd;
} else {
total_current_draw.value = oemdc1 + oemdc2 + oemdc3;
}
Look at this question: Get Radio Button Value with Javascript
You cannot get the value of a number of associated radio-buttons by just doing
document.getElementById(ID).value;
also look at this question, why you should not give the same id to multiple HTML elements: Why is it a bad thing to have multiple HTML elements with the same id attribute?
Now a possible simple solution for you problem (according to solution from first link):
You could write a function, which returns the value of your two radio-buttons:
function getPrismDrawValue()
{
// predefined result, if no radio button is checked.
// in this case result will be 0 -> "No"
var result = 0;
// get a list of all HTML-elements with the name 'include_prism_draw'
var radios = document.getElementsByName('include_prism_draw');
// loop through all this elements and check if one of them is checked
for (var i = 0; i < radios.length; i++)
{
if (radios[i].checked)
{
// get the value of the checked radio button
result = parseInt(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
return result;
}
Now your variable oemdc4 should be declared like this:
var oemdc4 = getPrismDrawValue();
EDIT to answer new question:
now your problem is here:
var oemdc4 = parseInt(document.getElementById("prism_draw").value);
if you pass 1.5 to parseInt()-function it will return 1.
use function parseFloat() instead to get your expected result.
var oemdc4 = parseFloat(document.getElementById("prism_draw").value);

Values of all textboxes on a page - without knowing the ID?

I am developing a Chrome Extension that, when the user leaves the page, saves all the text from the textboxes on that page and outputs it to a file.
If I knew the IDs of the textboxes on the page, then it wouldn't be a problem, but the issue is that I need the extension to get the values of all of the textboxes on the page without knowing the IDs, as it will be a different website each time the extension is used.
Also, how would the information be collected? In a string? It would be nice to go down the page and add each textbox to a file, one by one, instead of one huge string.
I've never used jQuery or understood it, and there's probably a solution in it staring me in the face. If anyone suggests using it, please could you explain it a little bit?
Thanks in advance. I would post my code, but I don't know where to start - ergo I don't have any.
you could store it in array using $.each, as :
var valsArr = [];
$("input[type=text]").each(function() {
valsArr.push( $(this).val() );
});
or create object with name as key and value as its value, like:
var valsObj = {};
$("input[type=text]").each(function() {
valsObj[this.name] = $(this).val();
});
You can do it like this:
function onClick(){
var areas = document.getElementsByTagName("textarea");
for(var i = 0; i < areas.length; i++){
alert(areas[i].value);
}
}
<textarea></textarea>
<textarea></textarea>
<button onclick="onClick()">Gather information</button>
Also see this regarding your "save to a file" question Using HTML5/Javascript to generate and save a file
Use the selector and apply it in an each cycle.
$(":text").each(function(){
alert($(this).val());
});
Make a for loop
for(i=0; i < $("input[type='text']").length; i++){
$("input[type='text']").index(i).value();
}
You can use .map() : It returns an array.
var arr = $(":text").map(function() {
return this.value
}).get(); //add join(',') after get() to get a simple comma separated list.
Instead of input[type="text"] you could also use :text pseudo selector.
Demo

Extract value from an attribute from each link and assign an onclick using the fetched value?

I'm learning JS but have hit a roadblock. I have links that have the attribute "number". I'd like to extract the value of "number" from each link, set it as a new variable, and then assign an onclick action to each link incorporating the corresponding value. I've been able to extract each value but don't know how to use them in the onclicks.
HTML
<a class="button call" href="#" number="6135555556">Call pager</a>
<a class="button call" href="#" number="6135555555">Call cell</a>
JS
var data = document.getElementsByClassName("call");
var numbers = '';
for (var i = 0; i < data.length; i++) {
numbers += data[i].getAttribute("number");
numbers[i].onclick = console.log("call " + numbers[i]);
}
If you want to the particular value on click of particular link then you can use this code.
var data = document.getElementsByClassName("call");
var numbers = [];
for (var i = 0; i < data.length; i++) {
data[i].onclick = getNumber;
}
function getNumber(){
numbers.push(this.dataset['number']);
alert(this.dataset['number']);
}
Here is the DEMO
There is no number property on anchor tag, so for your need we can use data-* property which allows you to store needful information on html.
This may not be entity correct, but assuming what you wanted was to console log the contained phone number whenever a link was clicked, there are probably 3 main changes you'd want to look at.
1) I'm guessing you wanted to connect your onclick event to the link element with the number in it data[i], rather to the number itself?
2) += will concatenate each found value on to the previous one. This may be what you wanted, although in the below code I've changed it only to log the current number
3) onclick expects to be passed a function, which it will then run when the click event is fired. Wrapping your console log in a function provides it to the onClick in the format it expects.
Assuming all that's right, the js to work with the above links should look something like this:
var data = document.getElementsByClassName("call");
for (var i = 0; i < data.length; i++) {
data[i].onclick = function() { console.log("call " + this.getAttribute("number")); }
}
Hope that helps :)
Edit: Updated the code to fix the bug james montagne pointed out below. The getAttribute is now performed within the context of the click event, meaning the issue with scoping is avoided. Sorry about that, completely missed the issue.

How do I get element's className inside loop of elements?

I am trying to create a function that given a divid, and a list of classes, will then do some text replacing inside them.
Having learned of how Firefox Dom is handling text nodes differently, I read that I had to use javascript to loop through the elements, sibling to nextSibling.
The last obstacle I had in my script, of which you see a small portion of, is getting the classname. I need the class name so that I can filter down what content get's text replaced.
Having looked all the answers, and with the help of a co-worker named Ryan at work, we have redone this in jquery.
$(divid).find(".status_bar").each( function() {
var value = $.trim($(this).text());
// if value is not defined thru browser bugs do not replace
if (typeof(value) != 'undefined') {
// it is a text node. do magic.
for (var x = en_count; x > 0; x--) {
// get current english phrase
var from = en_lang[x];
// get current other language phrase
var to = other_lang[x];
if (value == from) {
console.log('Current Value ['+value+'] English ['+from+'] Translation ['+to+']');
value = to;
$(this).attr('value', to);
}
}
}
});
This currently works in all areas, except in the replacing of text.
The reason I had originally with doing this in jQuery, had to be not sure I could loop thru elements, and avoid the problem with firefox and text nodes.
I am doing a loop of all elements inside a div, and I now need to get the classname of the element that I am looping by.
Then i can check if the current element's class is one, I need to do something with...
// var children = parent.childNodes, child;
var parentNode = divid;
// start loop thru child nodes
for(var node=parentNode.firstChild;node!=null;node=node.nextSibling){
var myclass = (node.className ? node.className.baseVal : node.getAttribute('class'));
}
But this code for getting the classname only get's null values.
Any suggestions?
For those of you who are trying to figure out what the whole point is, read this JavaScript NextSibling Firefox Bug Fix I have code that does my language translation that works in Google Chrome and IE. But when I use it in Firefox, and try to translate div content after ajax has loaded it, it fails because of the whitespace issue.
I really don't have a preference of jQuery or Pure Javascript, I just want a working solution.
Thank you all for being patient. I personally thought I was extremely clear in my description, I apologize if it wasn't. I wasn't trying to be obscure or make it difficult to get help. But please don't insult me, by implying I am trying to make it unclear.
Thanks.
Hm... You have jQuery but don't use it?
$(divid).children(".yourSpecialClassName").each( function() {
doSomethingWith(this);
});
To get the CSS class attribute value, this will do:
$(divid).children().each( function() {
alert(this.className);
});
Based on the function you posted now, you want this:
$(divid).find(".status_bar").each( function() {
$(this).text( function(i, text) {
var x = $.inArray(en_lang, $.trim(text));
if (x > -1) {
console.log('Current Value ['+text+'] English ['+en_lang[x]+'] Translation ['+other_lang[x]+']');
return other_lang[x];
}
return text;
});
});
And please, don't ever use "do magic" as a comment again. This is incredibly lame.
EDIT. This can be made much more efficient (superfluous console.log() removed):
$(divid).find(".status_bar").each( function() {
// prepare dictionary en_lang => other_lang
var dict = {};
$.each(en_lang, function(x, word) { dict[word] = other_lang[x]; });
$(this).text( function(i, text) {
var t = $.trim(text);
return (t in dict) ? dict[t] : text;
});
});
if you are using jquery you can do this:
$("#myDiv").find("*").each(
function(){
var myclass = $(this).attr("class");
}
);
Your sample code doesn't make sense.
$(this).attr('value', to);
'value' is an attribute of the tag, not the text content.
Did you really mean to do this instead?
$(this).text(to);
Also, you've re-edited your question, but you're still trying to loop through the child nodes using non-jQuery methods. You said "The last obstacle I had in my script, of which you see a small portion of, is getting the classname. I need the class name so that I can filter down what content get's text replaced."
If you are using jQuery it is completely unnecessary to loop through anything to get a class name. You simply have to use a proper selector in the first place.
$(divid).find(".status_bar.replaceme").each( function() {
// .replaceme is whatever class you're using for the stuff you want to change
// .status_bar.replaceme matches all elements with BOTH status_bar and replaceme classes
var value = $.trim($(this).text());
// if value is not defined thru browser bugs do not replace
if (typeof(value) != 'undefined') {
// it is a text node. do magic.
// NOTE: The following is inefficient but I won't fix it.
// You're better off using an associative array
for (var x = en_count; x > 0; x--) {
// get current english phrase
var from = en_lang[x];
// get current other language phrase
var to = other_lang[x];
if (value == from) {
console.log('Current Value ['+value+'] English ['+from+'] Translation ['+to+']');
// value = to; <-- useless, get rid of it.
$(this).text(to);
// or $(this).html(to);
}
}
}
});

Categories