resetting fields with jQuery - javascript

I am trying to reset fields (selects and textboxes) in a partial. Here is what I have so far:
var $inputs = $('#StudentTable :select');
$inputs.each(function () {
if ($(this).name = "TeachingAsstSelect") {
$('select[name="TeachingAsstSelect"]').each(function () {
$(this).text("");
})
}
else {
$(this).val("Select");
}
});
Here "TeachingAsstSelect" is being cleared, but other selects are not reset. Am I missing something? More importantly, Am I doing it the right way?

If you are trying to test equality of a string, you should use == or ===. See here form more on that: Which equals operator (== vs ===) should be used in JavaScript comparisons?
Also, as #Raminson suggests, try use the attr() method instead.
if ($(this).attr('name') == "TeachingAsstSelect") {
Or better yet, nesting .each() twice like that may not perform as well as other solutions.
I also notice that you are testing name in your if condition then using a jquery selector to match again on [name="TeachingAsstSelect"]. What about simplifying like this:
var $teachingAsstInputs = $('#StudentTable :select[name="TeachingAsstSelect"]');
$($teachingAsstInputs).text("");
var $otherInputs = $('#StudentTable :select').not('[name="TeachingAsstSelect"]');
$($otherInputs).val("Select");

For jQuery objects you should use attr() method, name is one of the DOM Element properties.
Change this:
if ($(this).name = "TeachingAsstSelect") {
to:
if ($(this).attr('name') == "TeachingAsstSelect") {
also note that for comparison you should use == operator, currently you are setting the value.

Related

How can I compare a variable to a number in an if statement using JavaScript?

I have tried to make an if statement to check if a variable is 2. But everytime I try, I get the else statement.
Here's my Javascript:
$(document).ready(function() {
$('#test').html(2);
var antkeepere = document.getElementById('test');
if(antkeepere==2){
$('#mer').html('Ja!')
}
else{
$('#mer').html('Nei!')
};
});
First I wrote 2 in my html, but it didn't work. THen I tried to make it 2 through js as in the example over, but it didn't work either. I have searched through other threads like this and tried to but .value both in the if statement and when creating the variabel, but none of them worked either.
document.getElementById() returns the DOM element, not its contents. To get its HTML content, you have to use the .innerHTML property. And to convert it to a number, you should use parseInt().
var antkeepere = parseInt(document.getElementById('test').innerHTML, 10);
Since you're using jQuery, you can stick with that:
var antkeepere = parseInt($("#test").html());
because document.getElementById('test'); returns a dom object.
try this
var antkeepere = $("#test").val();
You do like this in jQuery
$(document).ready(function() {
$('#test').html(2);
var antkeepere =$('test').html();
if(parseInt(antkeepere) == 2){
$('#mer').html('Ja!')
}
else{
$('#mer').html('Nei!')
};
});
Since you are putting the 2 using .html $('#test').html(2); you can also access that using the same function .html() but without the arguments.
If comparing the antkeepere variable to 2 you need to parse it so it's will convert it into a number because .html returns a string.
so that is why you need to do this if(parseInt(antkeepere) == 2)
If you are going to compare string you don't need to parseInt you can simply go like this if(antkeepere == 'aaab')
try below code
//As I understand test is div or span not input type objects. if it is input type element then use val() instead of html()
$(document).ready(function() {
$('#test').html(2);
var antkeepere = document.getElementById('test');
// use can also use parseInt($('#test').html())
if(parseInt(antkeepere.innerHTML)==2){
$('#mer').html('Ja!')
}
else{
$('#mer').html('Nei!')
};
});
Most of the answers above are pretty good, but seeing as you've already loaded jQuery, you may as well use it (you don't need document.getElement...).
$(document).ready(function() {
$('#test').text(2); // Using text() instead of html() just means you can write stuff like "&", instead of "&"
var antkeepere = parseFloat( $('#test').text() ); // parseFloat ensures the contents of test is converted to a number.
if(antkeepere == 2){
$('#mer').text('Ja!')
}
else{
$('#mer').text('Nei!')
};
});
First, you're not retrieving the html of #test but the whole element. Second, to make sure the html value is a number with value 2, you should try to convert the html value to a Number. A simple code adjustment:
$(document).ready(function() {
$('#test').html(2);
var antkeepere = Number(document.getElementById('test').html());
if(antkeepere === 2){
$('#mer').html('Ja!')
}
else{
$('#mer').html('Nei!')
};
});

Asserting all checkboxes are checked

I have 5 checkboxes with the same name property relative-view.
I want to assert that all of them are checked. I can do this to check the first and last one
expect(element.find('input[name="relative-view"]').first().prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]').last().prop("checked")).toBe(true);
But I don't know how to check them all. I have tried the following but I get an error saying undefined is not a function
expect(element.find('input[name="relative-view"]')[0].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[1].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[2].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[3].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[4].prop("checked")).toBe(true);
How can I do this?
[n] notation returns DOM elements which don't have .prop() - that's jQuery API. Use .eq():
var boxes = element.find('input[name="relative-view"]');
expect(boxes.eq(0).prop("checked")).toBe(true);
expect(boxes.eq(1).prop("checked")).toBe(true);
expect(boxes.eq(2).prop("checked")).toBe(true);
expect(boxes.eq(3).prop("checked")).toBe(true);
expect(boxes.eq(4).prop("checked")).toBe(true);
An alternative approach would be to use the standard .checked property:
var boxes = element.find('input[name="relative-view"]').get();
expect(boxes[0].checked).toBe(true);
expect(boxes[1].checked).toBe(true);
expect(boxes[2].checked).toBe(true);
expect(boxes[3].checked).toBe(true);
expect(boxes[4].checked).toBe(true);
Also, try just iterating over the jQuery collection:
$('input[name="relative-view"]', element).each(function () {
expect(this.checked).toBe(true);
});
You can write a function which will go through all checkboxes and return false if any of them is not checked. Use:
function CheckAllCheckboxes(){
var _RetValue = true;
$('input[name="relative-view"]').each(function(){
if($(this).prop("checked") != true)
_RetValue = false;
return false; // quit from each()
}
return _RetValue;
}
Then you can use
expect(CheckAllCheckboxes()).toBe(true);

How to add class to a jQuery element if a condition is true and remove the same class if the condition is false?

Is there a shorter way to do the following?
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
if (is_checked) {
select_all_checkbox.parent().addClass("selected");
} else {
select_all_checkbox.parent().removeClass("selected");
}
Use toggleClass, passing a second argument (a boolean) that specifies whether the class should be added or not:
select_all_checkbox.parent().toggleClass("selected", is_checked);
If you have multiple elements selected by input.select_all, you have to iterate over them though:
$("input.select_all").each(function() {
$(this).parent().toggleClass('selected', this.checked);
});
Absolutely! You can choose between the methods (addClass/removeClass) programmatically, and use the one that is returned when an expression is executed.
Like this:
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
select_all_checkbox.parent()[is_checked ? "addClass" : "removeClass"]("selected");

If condition on windows load not working in javascript

The following code is not working and cant understand why. What am I doing wrong?
$(function() {
var advanced = localStorage['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")|(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
Check the OR operator. It should be like -
if((advanced == "true")||(advanced==true)){
This expression is not working:
if((advanced == "true")|(advanced==true)){
It’s enough to do:
if(advanced) {
because "true" as a string is also "truthy".
You are missing an extra |:
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true") || (advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
OR operator needs to be two |..Like this:
if((advanced == "true") || (advanced==true)){
If the variable advanced is a BOOLEAN, then you can simply use this:
if(advanced) {
// code here..
}
I think there is mistake in your javascript code.so you can not use "|" instead of "||"
so try by the following code gets solved your error.
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")||(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
As you say that a proper OR operator is still not working, then I suspect it must be a problem with the case.
Check this fiddle: http://jsfiddle.net/VTfQU/
Use this code to simplify your if condition:
var advanced = localStorage.getItem['advanced-search'];
advanced = advanced.toString().toLowerCase();
if (advanced == "true") {
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = "false";
}
The idea is to convert your data into lowercase and then just check the condition on that value. I have added toString() just to be safe, anyway getting a value out of local storage will always be a string.

jquery each loop only looping once and if using else code stops

I've got two problems with the following javascript and jquery code.
The jquery each loop only iterates once, it gets the first element with the right ID does what it needs to do and stops.
The second problems is that when I use the else in the code the one inside the each function, it doesn't even tries the next if, it just exits there.
I'm probably doing something fundamental wrong, but from the jquery each function and what I'd expect from an else, I don't see it.
Javascript code:
var $checkVal;
var $checkFailed;
$("#compliance").live("keypress", function (e) {
if (e.which == 10 || e.which == 13) {
var checkID = $(this).parents('td').next().attr('id');
var checkVal = $(this).val();
$('#' + checkID).each(function () {
var cellVal = $(this).text();
if (checkVal == cellVal) {
$(this).removeClass("compFail").addClass("compOk");
} else {
$(this).removeClass("compOk").addClass("compFail");
var checkFailed = True;
}
});
if (checkFailed == 'True') {
(this).addClass("compFail");
} else {
(this).addClass("compOk");
}
}
});
How could I get the each loop to iterate through all instances of each element with the id assigned to the variable checkID, and get the code to continue after the else, so it can do the last if?
An id should appear on a page only once. If you want to have multiple elements with same id, then use a class, not an id.
Your each loop iter only once because you are selecting by id thus you are selecting only one element in the page. If you change you elements to a class it should work like you expect.
This is to illustrate what I'm talking about in my comment, so that you do not remove the wrong var:
var checkVal;
var checkFailed;
$("#compliance").live("keypress", function (e) {
if (e.which == 10 || e.which == 13) {
var checkID = $(this).parents('td').next().attr('id');
//HERE is the first edit
checkVal = $(this).val();
$('#' + checkID).each(function () {
var cellVal = $(this).text();
if (checkVal == cellVal) {
$(this).removeClass("compFail").addClass("compOk");
} else {
$(this).removeClass("compOk").addClass("compFail");
//HERE is the second
checkFailed = True;
}
});
if (checkFailed == 'True') {
(this).addClass("compFail");
} else {
(this).addClass("compOk");
}
}
});
Normally, the way you have it would cause a compile-time error (in a typed language like C#) for redeclaring a variable. Here, it's not clear to me if it will be used as a local variable (ignoring your global variable) or if javascript will combine them and consider them the same. Either way, you should use it as I have shown so that your intent is more clear.
EDIT: I have removed the $ from your variables (var $checkVal) as on jsFiddle it was causing issues. SO if you do not need those $'s, then remove them. Also, note that testing on jsFiddle indicates that you do not need to change your code (other than possibly removing the $ from your declaration) as javascript appears to consider them the same variable, despite the redeclaration, which I find a bit suprising tbh.
The jquery each loop only iterates once, it gets the first element
with the right ID does what it needs to do and stops.
Yes, this is absolutely right for the code you're using:
$('#' + checkID).each(function(){};)
ID attributes are unique. There must be only one element with a given ID in the DOM. Your selector can match only one element. You are iterating over a collection containing just 1 item.

Categories