I was trying to grab the results from this 3 elements, it updates every time I click a button
<span id="machine1Result" class="slotMachine noBorder">0</span>
<span id="machine2Result" class="slotMachine noBorder">0</span>
<span id="machine3Result" class="slotMachine noBorder">0</span>
with this code trying to grab the 3 combined values of the element, if matched I was able to do some changing:
var text = $('#machine1Result,#machine2Result,#machine3Result').text();
var comparingText0 = "000";
var comparingText1 = "111";
if (text == comparingText0) {
$('.wonbg').css({'background-image': 'url(img/won_bg.png)'});
$('.rw14').css({'backgroundColor': '#ff9900'});
count += 1;
}
if (text == comparingText1) {
$('.wonbg').css({'background-image': 'url(img/won_bg.png)'});
$('.rw1').css({'backgroundColor': '#ff9900'});
count += 1;
}
else {
$('.slotMachineButton').click(function() {
$('.wonbg').css({"background": "none"});
$('.rewards').css({"background": "none"});
});
}
the code above runs the condition properly if the elements has the same number, but it also functions even if there's one wrong number say 110 or 101 and vise versa, tried === giving me same results.
If the first condition is true, it will also fire the else. That is because this line
if ( text == comparingText1 ) {
should be an else if
else if ( text == comparingText1 ) {
and now all the conditions will be linked.
Bow the other issue is text is text()
var text = $('#machine1Result,#machine2Result,#machine3Result').text();
EDIT: since what you gave is wrong, I have to change the answer....
text)_ will only give the first answer, so you would need to loop through them
var results = $('#machine1Result,#machine2Result,#machine3Result');
results.each( function() {
var currentLine = $(this);
var currentText = currentLine.text();
console.log(currentText);
} );
i figured it out, the plugin http://plugins.jquery.com/slotmachine/ itself is causing late detection of the elements final result:
after the plugin stops and set the results there's a 1.3 sec delay before it writes the final result like let say 000 then it writes another 001, 011 finally the result 111 i notice it when injecting the alert(); it alerted me for more than 3 with different results, it also happening at console.log() by sending more than 4 to 5 request.
all i did is to set a timeout of 1.3 sec when the final result happens, so:
setTimeout(function () {
var results = $('#machine1Result, #machine2Result, #machine3Result').text();
var comparingText0 = "000";
var comparingText1 = "111";
if ( results == comparingText0 ) {
$('.wonbg').css({'background-image' : 'url(img/won_bg.png)'});
$('.rw14').css({'backgroundColor' : '#ff9900'});
count += 1;
}
else if ( results == comparingText1 ) {
$('.wonbg').css({'background-image' : 'url(img/won_bg.png)'});
$('.rw1').css({'backgroundColor' : '#ff9900'});
count += 1;
}
else {
$( '.slotMachineButton' ).click(function() {
$('.wonbg').css({"background" : "none"});
$('.rewards').css({"background" : "none"});
});
}
}, 1300);
Related
I am working on a Cardio Test calculator which calculates heart attack risk. I want to get score based value for each input. The results logic is already working, I just need to get result score value. See the code below.
<script>
$(document).ready(function() {
$("#female").change(function() {
if ($(this).is(":checked")) {
$("#femaleage").show();
$("#maleage").hide();
}
});
$("#male").change(function() {
if ($(this).is(":checked")) {
$("#maleage").show();
$("#femaleage").hide();
}
});
$( "#cardio__test" ).submit(function( event ) {
event.preventDefault();
if ($("#score").val() <= 3) {
$(".risk__score.low__risk").show();
}
if ($("#score").val() >= 4 && $("#score").val() <= 6) {
$(".risk__score.moderate__risk").show();
}
if ($("#score").val() >= 7) {
$(".risk__score.high__risk").show();
}
if ($("#maleage").val() >= 70) {
$("#score").val() + 8;
}
$(this).hide();
});
});
</script>
Here's a link!
I tested out your codepen and I found out the value of your score is a string type instead of int as I tested using parseInt() and typeof... and the result string value is blank (maybe i changed some code in the codepen during testing) How do you check the value of the score and do you get it as a number? Anyway, to print out the result value you can do it in many ways such as
adding a new div in your results div and print the results inside the div
$(".(new div class name) h3").text($("#score").val());
or simply alert the results
alert($("#score").val());
you can simply use
var scoreValue = $("#score").val();
I have this sample:
link
CODE HTML:
<label for="primary_phone">Primary Phone Number<span class="star">*</span></label>
<br>
<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input" value="" maxlength="10">
CODE CSS:
.invalid{
border:1px solid red !important;
}
.valid{
border:1px solid green !important;
}
CODE JS:
function phoneFormat(){
$( "._phone" ).on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
var testt=$(this).val().match(text);
if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
{
$(this).removeClass('valid').addClass('invalid');
}
else{
$(this).removeClass('invalid').addClass('valid');
}
$(this).val(text);
});
}
$( "#primary_phone" ).blur(function() {
phoneFormat();
});
I put a script that arranges text format
for example, we can add this number :
1234567890
After calling script appears next form (what is right)
(123) 456-7890
The problem is when you want to edit my phone number ... if you want to delete the last two numbers because I put the following code maxlength="10"
I want the user can not write more than 10 characters.
How do I fulfill both requirements.
If something is not explained well I'll do an edit to this post
Thanks in advance!
Just remove all special characters when you focus in on the input box:
$("#primary_phone").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,'');
$(this).val(value);
});
Now when you click out of the input box, your original function to format the number comes in to play :)
Working fiddle : https://jsfiddle.net/reko91/gto0qeyx/2/
I would set a higher maxlength (say 15) and bind the input to keypress.
Inside the event you can check the keyCode against a set of allowed ones and suppress the event (entry of the character) otherwise.
I would also suppress the entry of numbers if we already have 10 (with one exception: if the user selected (marked) a portion of the input and that selection contains numbers.
var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]
function keyCode(keyCode) {
if (alwaysAllowed.indexOf(keyCode) !== -1) {
return "allowed";
} else if (keyCode >= 48 && keyCode <= 57) {
// 0 - 9
return "number";
} else {
// any other character
return false;
}
}
function countNumbers(text) {
// return the number of characters [0-9] in the string "text"
var counter = 0;
for (var i = 0; i < text.length; i++) {
if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
counter++;
}
}
return counter;
}
$primaryPhone.on("keypress", function () {
var keyCodeEvaluation = keyCode(event.keyCode);
if (keyCodeEvaluation === false) {
event.preventDefault();
} else if (keyCodeEvaluation === "number") {
var value = this.value,
counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
//
if (counter === 0 && countNumbers(value) > 9) {
event.preventDefault();
}
}
});
This would allow the user to edit (or write) the phonenumber with your format applied.
MORE IMPORTANTLY
You should rewrite your phoneFormat() function.
Each execution adds another event listener. The first time you change the input value it executes one time. Then two times, three times and so forth.
You should also store objects you use repeatedly in a variable, e.g. $( this ) (creating the same jQuery object each time is a performance killer).
Here is a working example that should cover most of your use cases.
this is for a personal art project. What I basically want to do is create a blank web page where a user can type in text (like a text-editor), but have the text fade out as they type.
By fade out, I don't want the user to have the ability to see the text they had just written. So, I don't want to just transition the font color to match the background color as the user can select the text again.
So far, I've made a textarea that on keyup will store the text input, which will show in a separate div. I've specified in Javascript that when the entered text has reached a certain length: the div will fade out, clear the text, and show up again to show the current text input. The problem is that according to the console, I can't clear the value of the div. Does this make sense?
Here is a fiddle: http://jsfiddle.net/anelec/k40p72xk/5/
HTML:
<textarea type='text' id='myinput'></textarea>
<div><span id="fade"></span></div>
Javascript:
//on keyup store text input into a variable "text"
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
//show values of "text" variable in id "fade"
$("#fade").text(this.value);
var fade = $("#myinput").val();
//function to clear text value of id "fade"
function cleartext(){
document.getElementById("#fade").value="";
}
//clear text value of id "fade" after 15 letters
if (fade.length >=15) {
$("#fade").fadeOut(200);
cleartext();
}
//show the incoming text input somehow
if (fade.length <=15) {
$("#fade").fadeIn("fast");
}
});
Please let me know if there is a better way I can approach this.
Try something like this:
// Keep track of how many sets of 15 chars there are
var accum = 0;
// If the length is divisible by 15
if (text.length % 15 == 0) {
$("#fade").fadeOut(200, function() {
accum ++;
// $(this) refers to $("#fade")
$(this).val(''); // set the value to an empty string
});
} else {
$("#fade").fadeIn('fast');
}
// Use the substring method to get every 15 characters to display in #fade
var start = accum * 15,
end = (accum + 1) * 15,
next = text.substring(start, end);
$("#fade").text(next);
This is the closest I've gotten:
Javascript:
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
//show values of "text" variable in id "fade"
$("#fade").text(this.value);
var fade = $("#myinput").val();
if (text.length >=5) {
$("#fade").fadeTo(600,0);
$(this).val("");
$("#fade").fadeTo(20,1);
}
});
If I understood you correctly, this should work. You'll want to use the innerHTML instead of value.
Try changing:
function cleartext(){
document.getElementById("#fade").value="";
}
to this:
function cleartext(){
document.getElementById("#fade").innerHTML="";
}
You use value for input fields, and innerHTML for non-input fields.
Option 1:
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
$("#fade").text(this.value);
var fade = $("#myinput").val();
function cleartext(){
document.getElementById("fade").innerHTML="";
// you use value this time because it's input field
document.getElementById("myinput").value = "";
}
if (fade.length >=15) {
$("#fade").fadeOut(200);
cleartext();
}
if (fade.length <=15) {
$("#fade").fadeIn("slow");
}
});
Option 2:
THIS EXAMPLE IS FROM ALEX CASSEDY - IF ITS THE BETTER ANSWER, GIVE HIM CREDIT AND NOT MINE, I SIMPLY FIXED ONE THING ON IT SO IT WORKS.
$( "#myinput" ).keyup(function( event ) {
var text = $("#myinput").val();
console.log("event working");
console.log(text);
$("#fade").text(this.value);
var fade = $("#myinput").val();
// Keep track of how many sets of 15 chars there are
var accum = 0;
// If the length is divisible by 15
if (text.length % 15 == 0) {
$("#fade").fadeOut(200, function() {
accum ++;
// $(this) refers to $("#fade")
$(this).val(''); // set the value to an empty string
});
} else {
$("#fade").fadeIn('fast');
}
// Use the substring method to get every 15 characters to display in #fade
var next = text.substring(fade.length - 15);
$("#fade").text(next);
});
Sorry for the horrible title, Am terrible at wording these things.
What I am trying to do is quite simple I think.
I have a set of hidden letters that make up a word.
Below them is a selection of random jumbled up letters.
When people click one of the random jumbled letters I am filtering through the hidden letters and showing the corresponding letter.
What I need to do is, if someone clicks a letter, filter through the hidden letters and either return a "true" and show the letter or return a "false/null" and make an alert();
This is how I am filtering at the moment. I am confused as to where to place an if statement or if that is even the approach I should be taking.
And here is a fiddle (the hidden word is "Seal") - http://jsfiddle.net/GA7WB/
var $buttons = $('#letters span'),
$hidden = $('.letter');
$buttons.click(function(){
_selected = $(this).html();
$hidden.filter(function() {
return $(this).text() == _selected;
}).show();
});
You just need to check the length of the results returned by the filter:
// get matched elements
var matches = $hidden.filter(function() {
return $(this).text() == _selected;
});
// show them, or alert if none
if (matches.length > 0) matches.show();
else alert("There are no " + _selected + "'s");
See Fiddle
Try setting a flag if you find one:
var $buttons = $('#letters span'),
var $hidden = $('.letter');
$buttons.click(function(){
_selected = $(this).html();
var foundOne = false;
$hidden.filter(function() {
var retval = $(this).text() == _selected;
if (retval) foundOne = true;
return retval;
}).show();
if (!foundOne) {
alert("Nope");
}
});
FIDDLE http://jsfiddle.net/GA7WB/4/
I want to make a bit of code that will check the value of an input box, count how many letters there are in the input box and if the value is divisable by 4 then to insert a -
Its so when the user is entering a code, in automatically inserts - after every 4 letters :)
Thanks
$("input").keyup(function () {
if(this.value.replace(/-/g, "").length % 4 == 0) {
this.value += "-";
}
});
This seems to work in the way you want
$(document).ready(function() {
$("#search").keyup(function(){
var stringFull = $(this).val();
if(stringFull.replace(/-/g, "").length % 4 == 0 ){
$(this).val(stringFull+"-");
}
});
});