What is the correct way of addressing the id of an element in an if statement condition?
if($('id').val() == Reset)
var Submit_Status = $("#Reset").val();
else
var Submit_Status = $("#Nb_var97").val();
Thanks,
Neil P.
Since I can't see your HTML I'm going to post a simple example:
<div id="myID"></div>
if($("div").attr("id") == "myID")
{
//do stuff
}
if($('someSelector').attr('id') == 'Reset')
var Submit_Status = $("#Reset").val();
else
var Submit_Status = $("#Nb_var97").val();
if ( $('div').attr('id') == 'Reset' ) {
// do something
}
If you're trying to check the value of the ID property then you can get it using the attr method.
For example, if you were looping through all of the elements with the class foo and wanted to check for the id bar you could do this in your loops:
...
var id = item.attr("id");
if(id == 'bar')
{
}
Here's an example where all divs on the page are selected and each one has it's ID checked in turn:
var divs = $('div');
divs.each(function(index, value) {
var id = $(value).attr('id');
if(id == 'foo')
{
// Do foo work
}
else if(id == 'bar')
{
// Do bar work
}
Working example: http://jsfiddle.net/gZHMD/1/
Using a short form (ternary/conditional operator) instead of if
// element could be any html element but inputs have val and div, spans and suchlike don't have val
var Submit_Status = $('element').attr('id') == 'Reset' ? $("#Reset").val() : $("#Nb_var97").val();
Also, if you have multiple elements, then you have to select specific one, an example here.
Related
$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
var i;
for (i = 0; i < calloutArray.category.length; i++) {
$(this).hide();
if (checkboxName === calloutArray.category[i]) {
$(this).show();
}
}
});
}
});
});
To explain this function it basically listens to see if a checkbox has been clicked and then hides all the callouts on the page.
It then loops through each one of those checkboxes and checks which ones are true on the page. I then create a variable that stores the current checkbox value.
After this I then want to loop through each callout and pull its data from a data attribute.
I then loop through each string in the array and hide the callout no matter what. However if the callout has an array value that is the same as the checkbox value then I need to show it.
This seems to be working without the hide. However I need to hide the callouts if they do not hold the same checked category names which is where I'm running into problems.
The If statement seems to never return true if I have already hidden the callout. So the question is how do I show the callout if the selected checkboxes match one of the callout array strings but hide the callout if the string is not in the callout array.
From what I've understand, the following code is equivalent
$('.checkbox').on('change', function () {
$('.pagination, .callout').hide();
$('.checkbox:checked').each(function () {
var checkboxName = $(this).val();
$('.callout').hide().each(function () {
var calloutArray = $(this).data();
if (calloutArray.category.indexOf(checkboxName) !== -1) {
$(this).show();
}
});
});
});
Merge selectors having common actions(hide())
Use :checked pseudo-selector to select only checked elements
Use hide() on selector and then iterate over it using each()
Use indexOf to check if element is in array
You're showing/hiding your element on each iteration of the loop. That means the result of the last iteration wins, as though you hadn't done the earlier ones at all.
You can just use Array#indexOf to see if the name is in the array, and use the resulting flag to show/hide the callout:
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
E.g.:
$('.checkbox').on('change', function() {
$('.pagination').hide();
$('.callout').hide();
$('.checkbox').each(function() {
if ($(this).prop('checked') === true) {
var checkboxName = $(this).val();
$('.callout').each(function() {
var calloutArray = $(this).data();
$(this).toggle(calloutArray.category.indexOf(checkboxName) != -1);
});
}
});
});
Also note that
if ($(this).prop('checked') === true) {
is quite a long way to write
if (this.checked) {
Similarly, with inputelements, this.value is the same as $(this).val().
Let's say I have many of these in my content div : <cite class="fn">blabla</cite>
How can I check every cite tag's content (in this case: blabla) with class fn to see if it equals to "sometext" then change it's color to red ?
Very simple.
$('cite.fn:contains(blabla)').css('color', 'red');
Edit: though that will match "blablablabla" as well.
$('cite.fn').each(function () {
if ($(this).text() == 'blabla') {
$(this).css('color', 'red');
}
});
That should be more accurate.
Edit: Actually, I think bazmegakapa's solution is more elegant:
$('cite.fn').filter(function () {
return $(this).text() == 'blabla';
}).css('color', 'red');;
You can make use of the amazing .filter() method. It can take a function as its parameter, which will reduce the jQuery collection's elements to those that pass its test (for which the function returns true). After that you can easily run commands on the remaining elements:
var searchText = 'blabla';
$('cite.fn').filter(function () {
return $(this).text() === searchText;
}).css('color', 'red');
jsFiddle Demo
You could potentially do something like:
$('cite.fn').each(function() {
var el = $(this);
if (el.text() === 'sometext') {
el.css({ 'color' : 'red' });
}
});
This fires a function against each cite that has the class fn. That function checks if the current cite's value is equal to 'sometext'.
If it is, then we change the CSS color (text-color) property to red.
Note I'm using jQuery in this example, as you've specifically tagged your question jQuery. Ignore the downvote, this was applied before I edited a typo that I'd made (el.val() rather than el.text())
Without jQuery:
var elms = document.querySelectorAll("cite.fn"), l = elms.length, i;
for( i=0; i<l; i++) {
if( (elms[i].innerText || elms[i].textContent) == "blabla") {
elms[i].style.color = "red";
}
}
The following javascript (prototype 1.6) code hides all checkboxes on the page and inserts a div element with some css style and a click event to act as a fake-checkbox. It also looks out for a label next (or previous) the checkbox, to also trigger the same event.
When I click the div (fake_el) itself, everything works as expected, but when I try the same with the label, it only works one time. after that, the el isn't gonna change - as if it (the el) would be a value-parameter.
Any ideas here?
$$('input[type=checkbox]').each(function(el) {
if (el.visible()) {
var fake_el = new Element('div', { className:'checkbox checkbox_' + el.checked });
var label = (el.next() != null && el.next().tagName === 'LABEL' && el.next().readAttribute('for') === el.id) ? el.next() : undefined;
label = (el.previous() != null && el.previous().tagName === 'LABEL' && el.previous().readAttribute('for') === el.id) ? el.previous() : label;
var action = function(el) {
el.checked = (el.checked) ? false : true;
fake_el.className = 'checkbox checkbox_' + el.checked;
}
fake_el.observe('click', function() { action(el); });
if (label != null) { label.observe('click', function() { c.log(el); action(el); c.log(el); }); }
el.insert({ after:fake_el }).hide();
}
});
I changed a couple items and created a jsFiddle for this. First and foremost, c.log had to be changed to console.log for it to work for me :). After that, the only thing I changed was how the divs were added, since it wasn't working for me with insert. I set up some test data and away I went...
EDIT: Perhaps you don't have a non-label tag between two checkboxes and it is getting confused? Notice I have a br between label and the next checkbox, maybe you need to do something like that.
I'm trying to pick out the value of an input box using jquery.
No probs there
$('#id_of_my_input_box_1').val();
But I need several so decided to put them into a loop:
============
var config_total_instances = '==some value='
for (var x = 1; x <= config_total_instances; x++) {
if (isset($('#id_of_my_input_box_'+x).val())) {
alert($('#id_of_my_input_box_'+x).val());
}
}
============
If I submit the form and I've got say 10 input boxes, the code above doesn't alert a value if the relevant input box has value.
I'm using a function below to check for values.
============
function isset(my_variable) {
if (my_variable == null || my_variable == '' || my_variable == undefined)
return false;
else
return true;
}
============
Am I missing something vital..? :-(
Addition: I shoudl add that I'm askign why I don't get the value of
$('#id_of_my_input_box_'+x).val()
echoed out in my alert box
Extending #Faber75's answer. You can set a class name for all your text element and then use something like this
$("input:text.clsname").each(function(){
if (isset(this.value)) {
alert(this.value);
}
});
In your current code if you are assigning a string to config_total_instances then it will not work.
don't consider my message an answer, more of a tip.
For a simplier code you could consider adding a class to the textboxes you need to check.
For example adding to all the inputs you need to check the class="sample" you could the use the jquery selector $(".sample") , returning you all the items and then you could simply do
$(".sample").length to count the items and $(".sample")[0].val() (or similar) to get/test values.
Cheers
Have you tried this? (note that there are three =)
if (my_variable === null || my_variable == '' || my_variable === undefined)
As an alternative to this try
if (typeof(my_variable) == 'null' || my_variable == '' || typeof(my_variable) == 'undefined')
Maybe I'm misunderstanding, but can't you just get all the <input>'s in a <form> that aren't :empty if that's the end goal of what you're trying to accomplish?
$('form#some_id input:not(:empty)').each(function () {
// do something with $(this).val() now that you have
// all the non-empty <input> boxes?
});
Or if you're just trying to tell if the user left some <input> blank, something like:
$('form#some_id').submit(function (e) {
if ($(this).find('input[type="radio"]:not(:checked), input[type="text"][value=""], select:not(:selected), textarea:empty').length > 0) {
e.preventDefault(); // stops the form from posting, do whatever else you want
}
});
http://api.jquery.com/category/selectors/form-selectors/
I am toggling 'tr.subCategory1'and its siblings .RegText. at the same time I am trying to store its ids in the array like this list_Visible_Ids[$(this).attr('id')] = $(this).css('display') != 'none' ? 1 : null; (When I collapsed I need store 'null' in array at its id place, If I expand I need store I need store 1 at its id place). But everytime alert($(this).css('display')) showing block. How can I handle this?. So When I collapsed or expanded it is storing 1 only.
$(document).ready(function() {
$('tr[#class^=RegText]').hide().children('td');
list_Visible_Ids = [];
var idsString, idsArray;
idsString = $('#myVisibleRows').val();
idsArray = idsString.split(',');
$.each(idsArray, function() {
if (this != "" || this != null) {
$('#' + this).siblings('.RegText').toggle();
list_Visible_Ids[this] = 1;
}
});
$('tr.subCategory1')
.css("cursor", "pointer")
.attr("title", "Click to expand/collapse")
.click(function() {
$(this).siblings('.RegText').toggle();
$(this).siblings('.VolumeRegText').toggle();
//alert($(this).css('display'))
list_Visible_Ids[$(this).attr('id')] = $(this).css('display') != 'none' ? 1 : null;
});
$('#form1').submit(function() {
idsString = '';
for (var index in list_Visible_Ids) {
idsString += (idsString != '' ? ',' : '') + index;
}
$('#myVisibleRows').val(idsString);
form1.submit();
});
});
You aren't toggling the tr itself, only its siblings (with class .RegText and .VolumeRegText). You therefore have to check if these are visible when you are storing the state in the array. For this you can use .is(":hidden") on one of the siblings. The click function would then look like this
$('tr.subCategory1')
.css("cursor", "pointer")
.attr("title", "Click to expand/collapse")
.click(function() {
$(this).siblings('.RegText').toggle();
var isHidden = $(this).siblings('.VolumeRegText').toggle().is(':hidden');
list_Visible_Ids[$(this).attr('id')] = !isHidden ? 1 : null;
});
There is also a lot to comment on the rest of the code. In
$('tr[#class^=RegText]').hide().children('td');
skip the .children('td'), as you aren't using this selection.
list_Visible_Ids = []; should be declared using var.
Looping through idsArray, you are checking this != "" || this != null), which should be using && instead of ||.
$.each(idsArray, function() {
if (this != "" && this != null) {
$('#' + this).siblings('.RegText').toggle();
list_Visible_Ids[this] = 1;
}
});
There's also really no point in using the $.each() function instead of a regular JavaScript for-loop
It also seems you are using an old version of jQuery, since using the # in selectors was deprecated in version 1.3.