Ok hello guys here is my problem i was try to create a jPrompt but i can't understand how can i make a simple if ckeck. I find the code here and i crate it again.Now i want to do something simple, the user click the button and must enter a code for example number 123, and i must check if the number is 123(true) then run an sql query else run this function again unless the user click cancel button and not ok.
I need a good example to learn how t use if statement with Jquery, any simple idea beginner in (jQuery) sorry!!!.
This is what i have try
$("#prompt_button").click( function(e)
{
e.preventDefault();
/*
jPrompt is function which will show custom promt window.
It has three argument.
First argument is label text.
Second is the predefined value for promt.
Third is promt heading.
and has callback function which will perform exatra
code like what user enter.
*/
jPrompt('Type something:', 'Prefilled value', 'Prompt Dialog', function(r)
{
if(r!=123){jPrompt('Enter the right code plese: ');}
else jAlert('Confirmed: ' + r, 'Confirmation Results');
});
});
I don't really understand your problem. Can you supply any code?
I need a good example to learn how t use if statement with Jquery, any
simple idea beginner in (jQuery) sorry!!!.
An "if" statement is fundamental to any client/server language.(Maybe different syntax in some)
var i = 123;
$('.selector').click(function()
{
if(i == 123)
{
alert("Value is " + i);
}
});
Pretty basic click event with an "if" statement. It maybe a good idea to hit a book store or pluralsight.
//Edits
Please remember when creating the later part of an "if / else" statement it needs to be wrapped in curly braces "{}"
Regards,
Sorry guys the answer it was easy to find after 2-3 hours i was searching, and (now i will hit my head to the monitor in front of me), here is the code
$("#prompt_button").click( function(e)
{
e.preventDefault();
/*
jPrompt is function which will show custom promt window.
It has three argument.
First argument is label text.
Second is the predefined value for promt.
Third is promt heading.
and has callback function which will perform exatra
code like what user enter.
*/
jPrompt('Type something:', 'Prefilled value', 'Prompt Dialog', function(r)
{
if( r!=123 ) {$("#prompt_button").click();}
else{window.location.href = "http://stackoverflow.com"}
});
});
It's nice to loose 2-3 hours for something like that, it was simple just call, with the right way, the function (Programming for Dummies( <-This is for Me ). Thanks anyway guys.
Related
I have a small app with one form and one input field. When a user submits this form, I first want to see if the value only contains letters. If all is good, I want to pass the value on to a function.
Here's what I have:
$('form').on('submit', function(e) {
if ($('input').val().match(/^[a-zA-Z]+$/)) {
someFunction($('input').val());
} else {
// Error message or something else here
}
e.preventDefault();
});
I don't like writing $('input').val() twice (once in the conditional statement, and again if it holds true). Using this wouldn't work, since it's within a conditional statement and not some sort of function... Is there a way to not repeat code in this scenario?
Perhaps setting $('input').val() to a variable would be best?
Thanks!
Just do this:
var inputValue = $('input').val();
Bit old but I found this helpful : Not repeating selectors
var myvar = $('input');
As well as the clear discription :
basically every time you use $(someselector) you iterate through the dom. If you can you should store the element reference
I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)
I'm new to JavaScript, and I'm wondering how to embed "if" statements within alerts. Specifically, I'm working on a form, and I want the alert that appears after the user clicks "Submit" to display different messages depending on which elements of the user's input are problematic (if any). I know that I could do it the other way around (i.e., use a series of if statements to determine which alert to show), but I was hoping to be able to use "if/else" within the alert code itself. Thanks!
You don't want to use an alert. It's used exclusively to inform the user that something has occurred, and you can't exactly get feedback from it. What you should use instead is a prompt or a confirm. Using the confirm code will allow you to determine whether the user hit OK or Cancel. While this is very limited, it still functions in a manner similar to what you're looking for. For example
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
Using the prompt code will allow the user to input a value, which you can then append to a variable and use logic from there, such as
var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
{
x="Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
The standard syntax for the prompt function is
prompt("This text will appear in the alert box","This is the default value");
My source, as well as additional information, is available at W3schools
Edit - I forgot to mention that, if they're using a form you've made in javascript, it could be easier just to run a simple if/else statement that checks if all of the values they've input are not null and have the right datatype before allowing them to continue. Have the else be the alert, I suppose, if you're using the if to confirm validity, as opposed to a lack thereof.
Use a variable:
msg = "";
if (…)
msg = "error 1";
else if (…)
msg = "error 2";
[…]
if (msg.length)
alert(msg);
I was hoping to be able to use "if/else" within the alert code call
You could use the conditional operator, which is basically an else-if inside an expression - which means that the expression as a whole can be passed as an argument:
alert( /* condition */ ? "error 1" : "everything is fine" );
You can write something like
alert(condition ? "Text if true": "text if false");
But it wouldn't be the most readable code. The commented options of
alert(getAlertMessage(anyNeededValue));
or
if (cond) {
alert("true");
} else {
alert("false");
}
sound better. But if you really keen on that "if in the alert", here you have an inline function:
alert((function(){
if (cond) { return "Text when true";}
else {return "Text when false");})());
alert takes a string as an input. Which can come from a variable.
var message;
if ("condition1") {
message = "message1";
} else if ("condition2") {
message = "message2";
} else if ("condition3") {
message = "message3";
}
alert(message);
Unfortunately if is a statement, and can't be directly used as an argument. But you can use the ternary operator instead, which is an expression.
alert(if ("this") { "won't" } else { "work"} );
alert('but' ? 'this' : 'will');
This is also possible, altough I've never seen it used:
alert(
('condition1') ?
'result1' :
('condition2') ?
'result2' :
'result3'
);
I'm looking at the http://digitalbush.com/projects/masked-input-plugin/
I'm calling it like this:
$(control).mask('999-999-9999');
And I don't want it to throw away the users input if something is wrong, e.g. they haven't finished
[407-555-____]
If you leave the field after having typed this much, it clears it. I'd like to leave it so they can finish later.
I'm new to jQuery, and I've looked through his source, but I can't find any way to do that, nor can I find any way to edit it to accomplish what I want, because the code is arcane to my eyes.
Set autoclear option to false.
$(control).mask('999-999-9999', {autoclear: false});
It looks like I should just make the whole mask optional:
mask('?999-999-9999')
That way the control thinks what the user has is "valid" and I can continue. Even though it isn't really the optional part of the mask.
You should delete statement input.val(""); in checkVal() function for a proper solution.
If you're using minified version, you should search and delete statement:
if(!a&&c+1<i)f.val(""),t(0,k);else
Try update file jquery.maskedinput.js
In function function checkVal(allow) set parameter allow on true. Its help for me.
function checkVal(allow) {
allow = true; ///add this command
//..............
}
In addition to removing the input.val("") in checkVal() you can also change the call to clearBuffer.
In the original code it is: clearBuffer(0, len); removing all user input.
if you change this to clearBuffer(lastMatch + 1, len); the user input will be displayed, followed by the mask placeholders that are still needed to complete correct input.
I have also added a user message in the .bind. This works for us, as we are using the MaskedInput for exactly one type of input. I'm checking for any input going further than position 7, because that's where the user input starts.
Here is what I did:
.bind("blur.mask", function() {
// find out at which position the checkVal took place
var pos = checkVal();
// if there was no input, ignore
if (pos <=7) {input.val(""); clearBuffer(0, len);}
// if the user started to input something, which is not complete, issue an alert
if (pos > 7 && pos < partialPosition) alert("Tell the user what he needs to do.");
if (input.val() != focusText)
input.change();
})
Adding Placeholder could solve the problem.
$(control).mask('999-999-9999');
Add an empty place holder into mask. see below
$(control).mask('999-999-9999', { placeholder: "" });
which would replace _ on the input text field by default. so there would bot be any _ left if the input length is dynamic and not fixed.
Looking for into the pluging script the unmask method.
$('#checkbox').unmask();
I have this js code
elem=$(this);
var tester_names="";
tester_names=$("#release_tester_tokens").val();
alert(tester_names)
if (elem.attr('checked')==true)
**tester_names=tester_names+", "+ elem.attr("title");**
alert(elem.attr("title"))
alert(tester_names)
I want to have tester_names=tester_names+", "+ elem.attr("title"); to have the combination of testers_names (a,b,c,d,e) and elem.attr("title") (f) to become (a,b,c,d,e,f)
The alerts that I used is for debugging to see what values are stored in the variable.. They all store correctly, but they don't combine together when I call the bolded function... I just want to know why. I am using formtastic textarea instead of the normal textbox... do I have to adjust to that? Or maybe what the tester_names and elem.attr are outputting are of different type?
I tried it using this type of code (this is nearly the same with different variable names
function updateTextArea() {
var allVals = [];
$('.taglist :checked').each(function(i) {
allVals.push( $(this).val());
});
$('#video0_tags').val(allVals).attr('rows',allVals.length) ;
}
$(function() {
$('.taglist input').click(updateTextArea);
updateTextArea();
});
});
why does this add to checkbox values to the textarea perfectly whenever I check checkboxes when mine just outputs same results before and after using the starred function?
(I don't understand why ppl keep voting this down... its seems like a decent question after the first mishap and fix) :S
Use elem.attr('checked')=='checked' in if statement. There is no case elem.attr('checked')==true will be true. So the body of your if , will never be executed.