I need to multiply priceMonthly by 30, How can I do that in this "if" function? I am using it to echo the entered number live , but I need that number to multiply by 30. Dose someone have over ideas, or can someone guide me why its not working ?
function keyup_fill(ele, ele_place) {
$(ele).on("keyup", function(event) {
if ( $(ele).attr("name") === "priceMonthly" ) {
if (!$.isNumeric($(ele).val())) {
return ($(ele).val()*30); //not working
}
}
var newText = event.target.value ;
$(ele_place).html(newText);
});
}
keyup_fill("#priceMonthly", "#priceMonthly-place");
If what you want is to show in #priceMonthly-place the result of multiplying by 30 the value entered in #priceMonthly you can do this with the code (note that I'm assuming that both ids represent input elements):
function keyup_fill(ele, ele_place) {
$(ele).on("keyup", function(event) {
// I'm assuming that `ele` is an input.
var value = $(this).val();
if ($.isNumeric(value)) {
// I'm assuming that ele_place is an input.
$(ele_place).val(value * 30);
}
});
}
keyup_fill("#priceMonthly", "#priceMonthly-place");
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.
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);
Ok, I have a form with lots of different inputs, each has the same class name on it. What I need to do is loop though all of these inputs, which the user can add more to, with an AJAX call, making sure all inputs are four numbers only.
Now I can get it to check that it is of a length but when I try to add a check to make sure its a number, it does not seem to work, this is my current code:
var ValidMyData = function() {
$('#FORM-ID-HERE').on('submit',function(e) {
e.preventDefault();
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
$(Numbers).each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 ) {
return $(this).css("background-color","#FF0004");
} else {
return $(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
This works, if the inputs on my number field are not four in length, it makes the background color red, and then removes that background color if its then changed to be four.
I have tried some things but nothing as worked. I have mainly being playing with the IsNumeric() function, by adding that on my if check. Also, although this works, I don't think my return call is working right, I think I am doing something wrong but can not put my finger on it :). - When I console.log the CheckNumbers() inner function, I get undefined back.
All help most welcome.
Thanks
this code will check if it is 4 characters and if it's a number:
var ValidMyData = function() {
$('#FORM-ID-HERE').bind('submit',function(e) {
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
Numbers.each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 || !/([0-9])+/.test(String(GetCurrentInput))) {
return $(this).css("background-color","#FF0004");
e.preventDefault();
} else {
$(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
EDIT
I updated the answer using your own code, which now will submit the form if all the inputs are filled correctly, else it highlights it and doesn't submit the form.
i am validating the text box value on following conditions
It should be minimum of 3 characters
It should contain only alphabets
It should contain at least one vowel
If all the conditions get matches I am enabling the submit button.
If any of the above case are not matched I am setting an error message to div named error.
Here is my code
$document.ready(function(){
$('.tbox').focus(); // cursor in text box
$(':submit').attr("disabled",true); // disable generate button
$('.tbox').focus(fucntion(){
check_the_input()
});
});
function check_the_input()
{
var value = $(this).val();
$('.tbox').bind('keyup blur',function(){
$(this).val( $(this).val().replace(/[^a-z]/g,'') ); }
if(value.length > 3)
{
if(value.indexOf('a') == -1 && value.indexOf('e') == -1 && value.indexOf('i') == -1 && value.indexOf('o') == -1 && value.indexOf('u') == -1)
{
$('#error').text("*Input must contain atleast one vowel");
$(':submit').attr("disabled",true);
}
else
{
$(':submit').attr("disabled",false);
}
}
else
{
$('#error').text("*Input should be atleast 3 characters")
$(':submit').attr("disabled",true);
}
setTimeout(check_the_input,100);
}
I am facing following issues here:
If I type input as aa99 the input changes to aa , but still the generated button is enabled.
I am not getting the error at the time I type the text. Only after pressing tab or clicking mouse outside the textbox I am getting error.
I would suggest rethinking the approach. Consider this simpler example:
HTML:
<form>
<input type="text" id="myinput"/>
<button id="submit" type="submit" disabled>Submit</button>
<p class="error"></p>
</form>
jQuery:
By using a function test and an object to store your validation filters your code becomes more obvious, more elegant and you get better performance and it's easier to maintain for example to add new filters or more inputs.
Demo: http://jsbin.com/ezatap/6/edit
var $input = $('#myinput');
var $error = $('.error');
var $submit = $('#submit');
var Filters = {
min: {
re: /.{3,}/,
error: 'Must be at least 3 characters.'
},
char: {
re: /^[a-z]+$/i,
error: 'Must be only letters.'
},
vowel: {
re: /[aeiou]/i,
error: 'Must have at least one vowel.'
}
};
function test(value, filters) {
var isValid = false;
for (var i in filters) {
isValid = filters[i].re.test(value);
$error.hide();
$submit.prop('disabled', false);
if (!isValid) {
$error.show().text(filters[i].error);
$submit.prop('disabled', true);
break;
}
}
return isValid;
}
test($input.val(), Filters);
$input.on('keyup blur', function() {
test(this.value, Filters);
});
To the first question:
else
{
$('#error').text("*Input should be atleast 3 characters")
}
=>
else
{
$('#error').text("*Input should be atleast 3 characters");
$(':submit').attr("disabled",true);
}
To the second question:
When the input is being edited, no callback will be called until the input lost its focus.
If you would like to change the style of the :submit when editing, you can setup a periodically called function that checks the input every few milliseconds. here's a simple example:
function check_the_input( )
{
//routines check the input
//...
setTimeout( check_the_input, 100 ); //call me after 0.1 second
}
$(document).ready( function( ) { check_the_input( ) } );
of course there's more work to do if you want higher efficiency.
fix several error, see this: http://jsfiddle.net/4E7vv/2/