Javascript set attribute using variable - javascript

I'm unsure of the syntax here, but the code I have so far is this... (Note: I am passing the id's of three textboxes in the form '#begmile','#endmile','#totmile', and I want to set the value of the 'totmile' checkbox to endmile-bigmile)
function subtract(begmile, endmile, totmile){
y=$(begmile).attr('value');
z=$(endmile).attr('value');
y=z-y;
$(totmile).setAttr('value',???);
}
I'm not sure if my syntax here so far is correct, but assuming it is (that y is properly set to endmile-begmile, how do I use setAttr to set the value of totmile to the value of y?

This is the correct syntax:
var href = 'http://cnn.com';
$(selector).attr('href', href);

your last line isn't calling the right method:
$(totmile).setAttr('value',???);
should be:
$(totmile).attr('value',???);
e.g.
$(totmile).attr('value', y);//set the value to the variable "y"
you can also call .val(); instead to easily get the value of a field, or .val(newValue); to set the value.
also note that if your values for "y" and "z" are not actually representing numbers you'll get a weird result.

The value attribute refers to the default value for the textbox, not the current one. The current one is stored in the value property.
function subtract(begmile, endmile, totmile) {
document.getElementById(totmile).value =
document.getElementById(endmile).value - document.getElementById(begmile).value;
}
This also removes the need for jQuery, since the JavaScript Sledgehammer is far too excessive for this job. To make sure it works, just remove the # when you pass IDs to the function.

Related

problem with use of val() in jQuery sometimes failing and setting elements with array id's

I have a project where a form is required for inputs for a week, so for efficiency elsewhere an array of inputs is used (i.e. start[0] etc) this seems to have exacerbated the issue.
The problem is when validating a form where some inputs are given initial values (its an update) jQuery only returns those initial values instead of changed ones unless use of 'this' is feasible. I found to resolve that I had to use:
$(".weekdays").change(function(){
var newval = $(this).attr('value');
$(this).attr('value', newval);
});
Which seems a crazy thing to have to do! Its here I found using $(this).val(newval); always fails except when setting initial values, though its the common given solution?
In the same vein setting check-boxes seems also problematical, using:
var id = $(this).attr('pid');
$("#choice["+id+"]").prop('checked', false);
$("#choiceLabel["+id+"]").css('background-image','url("images/Open.png")');
Always fails, yet reverting to javascript with:
var id = $(this).attr('pid');
document.getElementById("choice["+id+"]").checked = false;
document.getElementById("choiceLabel["+id+"]").style.backgroundImage = 'url("images/Open.png")';
Works fine!
So does jQuery not like inputs with id's in array form? or am I getting things wrong somewhere?
When attempting to select an element with an id that contains special characters, such as [], you have to remember to escape them for jQuery. For instance..
var id = 12;
console.log(
$('#choice\\['+ id +'\\]').get()
);
console.log(
$('#choice[data-something]').get()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="choice[12]">weee</div>
<div id="choice" data-something>dang!</div>
Otherwise, jQuery will treat them as special characters, in this case, assuming you are trying to find an element that has an id and has an attribute matching your variable value.

jQuery won't count up variables

I have a little problem with my jQuery script: instead of counting up all variables, the script puts them next to each other. How do I count up the variables? (I am new to jQuery, so maybe I overlooked something or made a stupid mistake).
This is the line of code that should count up the variables.
totalcost = ((commissioncost + paypalcost) + qrticketcost);
http://jsfiddle.net/bsuh5q8k/1/
Thanks.
Often when you retrieve a value from a field using jquery's .val(), you'll get the string value (String type) instead of the numeric value you desire here. For instance, the field value may be 37.50, but you're getting "37.50" from .val()
So when you do this:
commissioncost = $('input[name=price]').val();
You'll get the String value.
So instead, try this:
commissioncost = Number($('input[name=price]').val());
This will convert/cast the value into a Number for you.
Also, a word of caution: just be sure whatever value is in that field, it can be evaluated as a Number, otherwise comissioncost will equal "NaN" (not a number) and will give you the same grief you're experiencing now. The rudimentary method to check if the type conversion was successful is:
commissioncost = Number($('input[name=price]').val());
if(isNaN(commissioncost)){
// oops, value wasn't a number!
}else{
// hooray! value was a number (most of the time - but that's a longer discussion)
}
commissioncost is being treated as a string. So when you add it thinks you're wanting to concatenate.
When you pull it from the input, explicitly tell Javascript that it's a number/float.
commissioncost = parseFloat($('input[name=price]').val());

Add an attribute on focus

What is the best way to add an attribute to an <input /> on focus using js / jQuery?
Right now, off the top of my head, I would think
$(document).ready(function(){
$('input').focus(function(){
$(this).attr(attributeHere);
});
});
Is that correct? Does the attribute have to have quotes around it?
Right now, it is just going to be an attribute with no value. Value will be added later.
This is what you can do :
$(document).ready(function(){
$('input').on("focus",function() {
$(this).attr('name', 'value'); // value could be '' if you would like to specify it later.
});
});
I hope it helps.
Looks fine to me. Only one thing I would add is that even if you want to leave the attribute empty, you should give it an empty string as a value.
var attrName = 'someAttr';
$(this).attr(attrName,'');
By not passing a value (even an empty string), you are actually calling the getter function for the attribute where you really want to be calling the setter.
You need to do this -
$(this).attr('attributeName','attributeValue');
What you are trying .attr(attributeName) is used to access attribute value
Description: Get the value of an attribute for the first element in
the set of matched elements.
See the api :
http://api.jquery.com/attr/
.attr( attributeName, value )
attributeName
Type: String <-- Either a var containing string or an "string"
The name of the attribute to set.
value
Type: String or Number
A value to set for the attribute.

Is there a way to remove a specific value from an attribute using jquery?

I have a page that displays products. In the encompassing <ul> I have some jQuery that adds values to attributes (such as <ul id="products" subcategorynavids="someValue">).
When a user clicks a filtering link, the jQuery checks the contents of subcategorynavids and then only displays products below that have a navid that is listed.
What I'm having an issue with is when the attribute has more than one value listed, and the user clicks the filter link a second time (to disable it), I need to remove ONLY the value that is being disabled...
For example, if the page is set to <ul id="products" subcategorynavids="9007 8019 7365"> and the user clicks the filter that enables/disables navid="8019", how do I remove the '8019' and leave the '9007' and '7365'?
I know there is .removeAttr(), .removeProp(), but those only remove the attribute ENTIRELY (right?).
I tried the following (which, as expected, didn't work)...
$("#products").attr('subcategorynavids').remove('8019');
There's no built-in jQuery way to do this, you'll have to do it manually.
$('#products').attr('subcategorynavids', function (_, val) {
return jQuery.grep(val.split(' '), function (val) {
return val !== '8019';
}).join(' ');
});
Here we use the callback way of using attr() to update an attribute. Inside the function, we split the current value val by ' ', and then filter the resulting array for those that aren't 8019 using jQuery'sgrep() function*, and the join the array back together and return it to be the new value of subcategorynavids.
* I'd want to use Array's filter() method, but it's not supported in all modern browsers, so you might as well use grep().
In this case, you could just use .replace()
var $attrs = $("#products").attr('subcategorynavids');
$("#products").attr( 'subcategorynavids', $attrs.replace( '8019', '' ));
use .replace()
$("#products").attr('subcategorynavids',$("#products").attr('subcategorynavids').replace('8019 ',''));
http://jsfiddle.net/laupkram/fg3dn/
Try this
var attr = $("#products").attr('subcategorynavids');
$("#products").attr('subcategorynavids', attr.replace('8019',''));
First get the values in that attribute and filter out the key word and again set the new attribute.. simple as that

Compare old values against the new values of Form

I have a form with several fields, one of which is "counter", that gets changed constantly. When the form is edited I need to track if some fields are changed and set the "counter" field to the number of modified fields up on submission. For example, if the old value of counter is 10 and field1, field2 and field3 are modified, then on form submit counter should be incremented to 13.
Below is what I'm attempting to do just for one field but its not working correctly. I also need to check not only one field but a few other fields too. Any help is appreciated. Thanks!
$(document).ready(function(){
var oldVal = getOldValue("field1");
var oldCounter = parseInt(getOldValue("Counter"));
var curCounter;
$('field1').change(function(){
var newVal= $(this).val();
if(oldVal.val() == newVal.val()){
curCounter = oldCounter +1;
setField("Counter", parseInt(curCounter));
}
});
});
Your if statement is incorrect. It fires when the value has changed (.change()), yet you are checking if the value is the same through if(oldVal.val() == newVal.val())
Also, .val() is a method of the jQuery object, so unless the function getOldValue() returns a jQuery object, your if statement is probably not going to do what you're expecting it to do.
What I'd do is store the oldValues of the form fields inside a data attribute of the formfield, so you can easily access it from within the .change() event, something like:
$(document).ready(function(){
var oldCounter = parseInt(getOldValue("Counter"), 10); // use the second argument '10' here or you might get strange results
var curCounter = oldCounter;
$('.field').each(function() {
// store the old value
$(this).data("oldValue", getOldValue($(this).attr("id")));
})
.change(function(){
// compare values, increase counter if it is different than the original value
if($(this).data("oldValue") != $(this).val()) {
curCounter++;
setField("Counter", curCounter);
}
});
});
Untested code but you get the gist, hope this helps
3 things i've noticed
*. you are checking the newVal's value twice, it should be something like
var newVal = $(this).val();
if (oldVal == newVal).....
*. for the oldValue variable you can just do var oldVal=$('#filed1_id').val(); this will be much simpler and will get you the value needed and not the object, this is simpler to handle.
*. you say you need to check for change on submission but you're checking on change, change it to which means you'll be checking more often when you need to.
and again, it will be nice to know what's getOldValue does.
good luck
I assume you want to know whether the user modified any fields when the form is submitted. It would be easiest to use .data() to keep track of which fields have changed from their original value. As other posters have mentioned your code calls .val() redundantly, incorrectly uses == instead of !=, and might not be using jQuery objects correctly.
This fiddle should address your issues: http://jsfiddle.net/EYjxP/

Categories