Display Based on innerHtml number - javascript

I want to create a system that displays certain content based on the number for this innerhtml content...
Here's the actual element itself, 17 is just the number for mine it is different for each user:
<span id="your_div_id_diamonds"><dd><div class="field_uneditable">17</div></dd></span>
I want it to display if their number is say between 10 and 20... Here's a code I've been trying to work with, but it only does one number at a time and currently isn't working...
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML = "17") {
document.getElementById('elitecontent').className="gotelite";
}
else {
document.getElementById('elitecontent').style.display="none";
}
}
});
Here's a version that works, but again only works for one number at a time... It'd be a huge pain if I had it go up to say 150 or 200, I'd have to make like 200 else if statements.
$( "#lev1" ).load('/u' + _userdata.user_id + ' #field_id-14 dd', function() {
var divs= document.getElementsByClassName('field_uneditable');
for (var i = 0, len = divs.length; i < len; ++i) {
if(divs[i].innerHTML.indexOf("7") != 1) {
document.getElementById('elitecontent').innerHTML="Elite";
}
else if(divs[i].innerHTML.indexOf("16") != -1) {
document.getElementById('elitecontent').innerHTML="Elite";
}
else if(divs[i].innerHTML.indexOf("17") != -1) {
document.getElementById('elitecontent').innerHTML="Elite";
}
else {
document.getElementById('elitecontent').innerHTML="Starter";
}
}
});
I basically want a code that works similar to with values, where I can just put something like >=10 and =<20

The problem you are facing with your current code is that you aren't using the correct comparison statements = is declarative, not used for comparison. In its place you should be using ==(matches regardless of data type) or === (must match data type as well) for instance
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML = "17") {
document.getElementById('elitecontent').className="gotelite";
}else {
document.getElementById('elitecontent').style.display="none";
}
}
});
should be
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML == "17") {
document.getElementById('elitecontent').className="gotelite";
}else {
document.getElementById('elitecontent').style.display="none";
}
}
});
However, for your needs something along the lines of:
$(function() {
if(document.getElementById('your_div_id_diamonds').innerHTML <=20 && document.getElementById('your_div_id_diamonds').innerHTML >=10) {
document.getElementById('elitecontent').className="gotelite";
}else {
document.getElementById('elitecontent').style.display="none";
}
}
});
should work.

Related

how to make alerts appear if the number of infant is more than adults

I want to make the alert appear if the number of infant is more than adults.
I've tried but it looks like something went wrong.
Please help.. thanks before
ex: http://jsfiddle.net/pBxfX/132/
var button = $('#submit'),
adult = $('#adult option:selected').val(),
infant = $('#infant option:selected').val();
if(adult > infant) {
$("#alert").hide;
}
else if(adult == infant) {
$("#alert").hide;
}
else {
$("#alert").show;
}
A few things:
You need to treat hide and show as methods (call them as .hide() and .show())
You need to execute your checking code in the change event handler for the select.
When comparing adults to infants, you need to treat them as integers (they are currently being treated as strings).
See http://jsfiddle.net/pBxfX/133/ for updated code
var button = $('#submit');
$(document).ready(function() {
$(button).attr('disabled', true);
$('input[type="text"]').on('keyup', function() {
var from = $("#from").val(),
to = $("#to").val();
if (from != '' && to != '') {
$(button).attr('disabled', false);
} else {
$(button).attr('disabled', true);
}
});
// Run code when any <select> changes
$("select").on('change', function() {
var adult = parseInt($('#adult option:selected').val()); //convert to integers for comparison
var infant = parseInt($('#infant option:selected').val()); //convert to integers for comparison
if (adult > infant) {
$("#alert").hide(); //Note that it is .hide() not .hide
} else if (adult == infant) {
$("#alert").hide();
} else {
$("#alert").show();
}
});
});
hide() and show() are functions so you need to add () to call these functions.
if(adult > infant) {
$("#alert").hide();
}
else if(adult == infant) {
$("#alert").hide();
}
else {
$("#alert").show();
}

How to refactor long if statment?

I have a long if statement that I'm wanting to refactor. The statement listens for a click and then updates one of five text boxes depending on if those text boxes have anything in them or not. How could I change my code to be more efficient.
$('#img1').click(function() {
if ($('#card1').val().length === 0) {
$('#card1').val('A feeling of warmth');
} else if ($('#card2').val().length === 0) {
$('#card2').val('A feeling of warmth');
} else if ($('#card3').val().length === 0){
$('#card3').val('A feeling of warmth');
} else if ($('#card4').val().length === 0){
$('#card4').val('A feeling of warmth');
} else if ($('#card5').val().length === 0){
$('#card5').val('A feeling of warmth');
}
});
you could use a loop
$('#img1').click(function() {
var items = ["#card1", "#card2", "etc"];
for(var i=0;i<items.length;i++){
if ($(items[i]).val().length === 0) {
$(items[i]).val('A feeling of warmth');
}
}
});
it's at least easier to read. Also if your buttons are always card + a number you could make it even simplier (not easier to read, just less lines & maintenance)
$('#img1').click(function() {
for(var i=0;i<=5;i++){
if ($("#card" + i).val().length === 0) {
$("#card" + i).val('A feeling of warmth');
}
}
});
It seems like you're using JQuery. You can use a selector and a filter to isolate the first empty item:
$('#img1').click(function() {
$('input:text[id^=card]')
.filter(function() { return $(this).val() == ""; })
.first()
.val('A feeling of warmth');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="img1">CLICK ME</button><br>
<input id="card1"><br>
<input id="card2"><br>
<input id="card3"><br>
<input id="card4"><br>
<input id="card5">
$('input:text[id^=card]') selects all text inputs whose IDs begin with 'card'. But the same principle would apply to other element types.
$('#img1').click(function() {
// num can be total count of the element like $(.card).children.count
var num = 5, // preferably dont make it hardcoded.
str = 'A feeling of warmth',
preIdStr = '#card',
id;
for (var i = 1; i <= num; i += 1) {
id = preIdStr + i;
if ($(id).val().length === 0) {
$(id).val(str);
}
}
});
Give all cards the same class.
Then use the selector $('.yourclass')
Now use the jQuery for-each (.each) function to iterate all elements. Within the loop you check the value, set it to whatever you want and return false when the value was set, since this exit's the loop.
$('.yourclass').each(
function () {
if (this.val().length === 0) {
this.val('your value');
return false; // exit loop
}
});

Simple If statement for Javascript(jQuery)

I am trying to wrap my head around if statements. I am new to this.
I have a pretty simple script pulling data(text) from a html5 data attribute.
var $datatext = $(this).data('explain');
Now I want an if statement when html5 attribute data-explain is missing or empty.
var $success = if ($datatext < 0) {
// show some other text, maybe? =
$(this).text('Fail');
} else {
// show original, maybe? =
$(this).text($datatext);
}
Again, hard time wrapping my head around it. Ohhh these ifs.
That should work:
if (typeof $datatext !== 'undefined' && $datatext.length > 0) {
$(this).text($datatext);
} else {
$(this).text('Fail');
}
check for the length not for the data in $datatext rewrite your code like this
if ($datatext.length > 0) {
// show original, maybe? =
$(this).text($datatext);
} else {
// show some other text, maybe? =
$(this).text('Fail');
}
You can do it this way,
Live Demo
$('.someclass').each(function() {
if(typeof this.attributes['data-explain'] != 'undefined')
{
alert(this.id + ": explain exists");
explain = $.trim(this.getAttribute('data-explain'))
if(explain.length > 0)
alert(explain);
else
alert("no value for explain");
}
else
alert(this.id + ": explain does not exists");
});​

problem in run some js codes after click

why after search and click on result search and click on plus(button add input) in the example on part Adding input, Date formating($('.find_input').delegate('input.date:text', 'keyup', ....) and normal number formatting($('.find_input').delegate('input.numeric:text','keyup',...) not work.
EXAMPLE: http://www.binboy.gigfa.com/admin/tour_foreign/insert_foreign
Js full code: http://jsfiddle.net/ZpDDR/
...
///// Date formating /////////////////////////////////////////////////////////////////////////////////////////
$dateSet = 0;
$monthSet = 0;
$yearSet = 0;
$('.find_input').delegate('input.date:text', 'keyup', function () {
$val = $(this).val().replace(/[^\d]+/g, "").match(/\d{1,12}$/);
if($val == null) {
return;
} else {
$val = $val.join("");
}
if($(this).val().match(/\d{4,}$/) && $val.length%2 == 0) {
$val = $val.match(/\d{2}/g);
if($yearSet < $monthSet) {
if($val.length == 4) {
$(this).val($val.join("").replace(/(\d{2})(\d{2})(\d{4})$/,'$3/$1/$2'));
$yearSet++;
} else if($val.length == 6){
$(this).val($val.join("").replace(/(\d{4})(\d{2})(\d{2})(\d{4})$/,'$4/$2/$3'));
$yearSet++;
}
} else {
if($monthSet < $dateSet) {
$(this).val($val.join("").replace(/(\d{4})(\d{2})(\d{2})(\d{2})$/,'$1/$4/$3'));
$monthSet++;
} else {
if($val.length == 2) {
$(this).val($val.reverse().join("/"));
$dateSet++;
$monthSet++;
} else {
$(this).val($val.join("").replace(/(\d{4})(\d{2})(\d{2})(\d{2})$/,'$1/$2/$4'));
$dateSet++;
}
}
}
}
});
///normal number formatting/////////////////////////////////////////////////////////////////////////////////////////
$('.find_input').delegate('input.numeric:text','keyup',function () {
$val = $(this).val().match(/[0-9]/g).reverse().join("").match(/[0-9]{1,3}/g).join(",").match(/./g).reverse().join("");
$(this).val($val)
});
The problem is that the element that you're delegating from,.find_input, doesn't exist yet when you're setting up the delegation function. delegate allows for defining event handlers for elements that aren't created yet, but only elements that match the second selector E.g., $('#must-exist-now').delegate('.can-be-created-later', ...);
I'm not sure if I described that well, but the solution is to change your statement to delegate from something that already exists on DOM load. For example: $(document).delegate('input.date:text', ...).

For textbox/textarea limit the length of input on typing, but not on paste

I got a strange requirement:
function TextLimit(elem, maxChars) { ... }
Where elem is a textarea or input of type=text and maxChars is the maximum number of characters that could go into the elem. The code inside the function must limit the length of the text inside elem to maxChars when the user is typing. However, if the user is pasting for the first time, the elem must take everything that was pasted even if the pasted text has more characters then maxChars.
EDIT: If the pasted text is longer then maxChars, then after pasting for the first time, the user can't type/paste anymore, unless the text is deleted/backspaced to a length smaller then maxChars.
Any suggestions using plain JavaScript or jQuery would be appreciated.
The maxlenght attribute doesn't allow for pasting. Setting/removing it programmaticaly on paste, doesn't work well in all browsers. Taking substring of elem's value on keydown/keypress/keyup produces some funky results.
Something like this seems to work:
Couple of things to work out still, like allowing the delete key if the max is reached. Should be easy fixes though.
Try it out: http://jsfiddle.net/wxUZz/7/ (updated)
function TextLimit(elem, maxChars) {
var permittedKeys = [8,37,38,39,40,46];
elem.focus(function() {
if(elem.val().length >= maxChars) {
elem.data('prevent', true);
elem.data('value', elem.val());
}
});
elem.blur(function() {
if( elem.data('prevent') ) {
elem.val( elem.data('value') );
}
});
elem.keydown(function(event) {
var count = elem.val().length;
if(count >= maxChars && $.inArray(event.which, permittedKeys) < 0) {
elem.data('prevent', true);
elem.data('value', elem.val());
return false;
} else {
elem.data('prevent', false);
}
});
}
TextLimit($('#myTextarea'), 30);
function TextLimit(elem, maxChars) {
var permittedKeys = [8,37,38,39,40,46];
elem.focus(function() {
if(elem.val().length >= maxChars) {
elem.data('prevent', true);
elem.data('value', elem.val());
}
});
elem.blur(function() {
if( elem.data('prevent') ) {
elem.val( elem.data('value') );
}
});
elem.keydown(function(event) {
var count = elem.val().length;
if(count >= maxChars && $.inArray(event.which, permittedKeys) < 0) {
elem.data('prevent', true);
elem.data('value', elem.val());
return false;
} else {
elem.data('prevent', false);
}
});
}
TextLimit($('#myTextarea');

Categories