Hello, I want a popup when the value of my input changes. I tried this, my test of my input :
<input onchange="maFonction()" id="result" readonly="readonly" type="text" value="0" size = "10" />
my function
maFonction = function(){
$.post("yourFile.php");
}
yourfile.php
<?php
$a = 40 ;
if ($result > $a) {
?>
<script> alert("yay!"); </script>
<?php } elseif ($result == $a) {
?>
<input onclick="s(this.form);" type="button" value="sauvegarder" />
<?php
} else {
?>
<script> alert("boooo!"); </script>
<?php
}
?>
I explain the readonly : it is like a calculator : I have many (7) inputs, I can stock values and the readonly is the total. So I need a msg when it is under 40, when it is equal, and when it is over 40.
Thanks for help cause for the moment I don't have any error I just have the popup boo when my page refreshes after nothing.
As I said in my remark, you don't need server-side code to do this. Here's a fiddle to do it with jQuery. Very easy :
HTML :
<input type="text" id="myInput"/>
Javascript (supposing you included jQuery) :
$('document').ready(function() {
$('#myInput').on('change',function(){
if(isNaN(this.value))
alert("Please enter a number");
else
{
var a = 40;
var myNumber = parseInt(this.value);
if(myNumber > a) alert("yay!");
else if (myNumber == a) alert("equals!");
else alert("boooo!");
}
});
});
I think the code is quite easy to understand. Note that you have to leave the text field for the "change" event to trigger, and it supposes you actually changed something. You could use blur event if you want to trigger each time and not only when value changed.
If you want or need to do that kind of check server-side (it may not be that easy than comparing 2 numbers), you can indeed use AJAX. But in that case I would advise to return XML , JSON or even an unformatted string from your server-side code, and treat the response in javascript. For example, you could return simply 'bigger', 'smaller','equal' , and act accordingly in the success event of your AJAX call. But that's for another lesson ;-)
EDIT following remark of OP :
HTML
<input type="text" id="input1" /><br/>
<input type="text" id="input2" /><br/>
<input type="text" id="input3" /><br/>
<input type="text" id="myInput" readonly="readonly"/>
Javascript :
$('document').ready(function() {
$('#input1,#input2,#input3').each(function() {$(this).on('change',recalculate);}
);
});
function recalculate()
{
if(isNaN(this.value))
alert("Please enter a number");
else
{
var a = 40;
var value1 = $('#input1').val().trim() == "" ? 0 : parseInt($('#input1').val());
var value2 = $('#input2').val().trim() == "" ? 0 : parseInt($('#input2').val());
var value3 = $('#input3').val().trim() == "" ? 0 : parseInt($('#input3').val());
var total = value1 + value2 + value3
$('#myInput').val(total);
if(total > a) alert("yay!");
else if (total == a) alert("equals!");
else alert("boooo!");
}
}
The fiddle
And if you wish to calculate and alert only when all 3 fields have been filled :
$('document').ready(function() {
$('#input1,#input2,#input3').each(function() {$(this).on('change',recalculate);}
);
});
function recalculate()
{
if(isNaN(this.value))
alert("Please enter a number");
else
{
if($('#input1').val().trim() !== "" && $('#input2').val().trim() !== "" && $('#input3').val().trim() !== "")
{
var a = 40;
var value1 = $('#input1').val().trim() == "" ? 0 : parseInt($('#input1').val());
var value2 = $('#input2').val().trim() == "" ? 0 : parseInt($('#input2').val());
var value3 = $('#input3').val().trim() == "" ? 0 : parseInt($('#input3').val());
var total = value1 + value2 + value3
$('#myInput').val(total);
if(total > a) alert("yay!");
else if (total == a) alert("equals!");
else alert("boooo!");
}
}
}
The fiddle
Related
Can anyone tell me what's wrong and how to fix this bit of code...
I am trying to bring up a message and not go to the next page, if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).
This is the bit of code I am having issues with:
if (country == '0' || country == "Send From...") {
error = 1;
jQuery('.msg').text("Please Select A Country.");
}
I think I have an issue with the OR function as it works without the || country == "Send From...".
<script>
jQuery(document).ready(function(){
jQuery('.submit').click(function() {
var error = 0;
var country = jQuery('#send_country').val();
var countrys = jQuery('#delv_country').val();
var idsa = jQuery('.size').val();
if (country == '0' || country == "Send From...") {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (countrys == '0') {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (error) {
return false;
} else {
return true;
}
});
});
</script>
if the #send_country box has either nothing in it or says "Send From..." (as its the placeholder).
The placeholder attribute is different than the value, you couldn't get the placeholder using .val(); instead you should use .prop('placeholder') :
var country_placeholder = jQuery('#send_country').prop('placeholder');
So the condition will be :
if (country == '0' || country_placeholder == "Send From...") {
But like this the condition will always return true since the placeholder will not change if you're filling the field, so i suggest just to check if the value is empty or '0' :
if (country == '0' || country == "") {
Hope this helps.
jQuery('.submit').click(function() {
var error = 0;
var country = jQuery('#send_country option:selected').val();
if (country == '') {
error = 1;
jQuery('.msg').text("Select A Country.");
}
if (error) {
console.log('EROOR');
} else {
console.log('SUBMIT');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select type="text" id='send_country'>
<option value="" disabled selected>Send From...</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<button class='submit'>Submit</button>
</form>
<span class='msg'></span>
I am new to php and jquery. I want validation for input type text.
<input type="text" size="5" name="add_qnty[]" value="">
I have tried the server side scripting but no use. So please help me
so that my submit will redirect only if all textboxes will fill with data.
Try this:
Add 'class=required' to all the required fields in the form and send these fields as an array to the below function like:
checkFrmFill( $( "#formid").find(".required"));
and the function will be:
function checkFrmFill(inputs) {
var returnVal = true;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "text" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].tagName == "SELECT" && ( inputs[i].value == "select" || inputs[i].value == 0 ) || inputs[i].value == "" || inputs[i].value == null) {
returnVal = false;
} else if (inputs[i].type == "password" && inputs[i].value == "") {
returnVal = false;
} else if (inputs[i].type == "textarea" && inputs[i].value == "") {
returnVal = false;
}
}
return returnVal;
}
This will return false for those fields that are blank.
For every text input add required attribute at the end of the tag.
<input type="text" size="5" name="add_qnty[]" value="" required>
<input type="text" size="5" name="add_qnty[]" value="" required>
refer http://www.w3schools.com/tags/att_input_required.asp
HTML
...........................
form id ='frm'
submit button id ='submit_frm'
SCRIPT
.............................
$(function(){
$('#submit_frm').click(function(){
$('#frm').find('em.err').remove();
$('#frm').find('input[type=text]').each(function(){
if($(this).val()==''){
$(this).parent().append('<em class="err">This field is required</em>');
}
});
if($('#frm').find('em.err').length > 0 ){
return false;
}else{
return true;
}
});
});
Try this: Working Example JSFIDDLE
$("form").on("submit",function(){
var len = $("input[name='add_qnty[]']").filter(function() {
return !this.value;
}).addClass("has-error").length;
alert(len);
if(len == 0){
return true; // Submit form
} else {
return false; // Validation failed
}
})
I have a problem similar to this resolved question here link!
There are many great answers in this link even extending the OP's problem to multiple radio groups.
(My formatting is the same as in the link but) my problem is that I don't have more than two radio groups, but rather multiple elements in my radio groups using a FOREACH loop.
My PHP is below followed by the script.
<?php
$query = mysqli_query($con, "SELECT example
FROM example_DB ");
while ($row = mysqli_fetch_assoc($query)){
foreach($row as &$value) {
if ($value == NULL) {
echo "";
}
else {
?>
<form method="post">
<input data-group="A" class="A" type="radio" value="<?php echo"$value<br />\n";?>">
<?phpecho"$value<br />\n";}}}?>
</input>
</div>
<div>
<?php
$query = mysqli_query($con, "SELECT example
FROM example_DB");
while ($row = mysqli_fetch_assoc($query)){
foreach($row as &$value) {
if ($value == 0.00) {
echo "";
}
else {
?>
<input data-group="A" class="A" ID="A" type="radio" value="<?php echo"$value<br />\n";?>">
<?php
echo"$value<br />\n";
}}}
?>
</input>
</div>
</form>
Im using the script that came with one of the answers in the link:
<script>
$( document ).ready(function() {
$(function() {
var radios = $('[type=radio]');
$('input:radio').change(function(){
var index = $( this ).index( $('[name=' + this.name + ']') );
var groups = [];
radios.not( $('[name=' + this.name + ']') )
.each(function(v,i) {
$.inArray(this.name, groups) > -1 || groups.push( this.name );
});
$.each(groups, function(i,v) {
$('[name=' + v + ']').eq( index ).prop( 'checked', true );
});
});
});
});
</script>
Try this : You can read the name of selected radio button and find all radio button with same name to select them.
NOTE - $(document).ready(.. and $(function(){.. both are same, so you can use any one of them and not both at same time.
$(function() {
$('input:radio').change(function(){
var name = $(this).prop('name');
$('input:radio[name="'+name+'"]').prop('checked',this.checked);
});
});
EDIT- As OP want to select all radio button with same class name or value, use following code -
For Same Class -
$(function() {
$('input:radio').change(function(){
var className = $(this).prop('class');
$('input:radio[class="'+className +'"]').prop('checked',this.checked);
});
});
For Same Value -
$(function() {
$('input:radio').change(function(){
var radioVal = $(this).val();
$('input:radio[value="'+ radioVal +'"]').prop('checked',this.checked);
});
});
i've created exception using JS so that user are only allowed to input numbers to the html form field. this is working nicely but the problem is, the Submit button isn't working anymore. if i remove the exception code, submit button is working nicely! i can't understand where is the problem. anyone can help please? thanks in advance!
here is the exception:
function validateNum(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate()
{
if( document.myForm.ic.value == "" ||
isNaN( document.myForm.ic.value ) ||
document.myForm.ic.value.length != 12)
{
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
}
here is my html form action:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="return(validate());">
and here is the input field & submit button:
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
Try this one as my explanation on my comment on your question:
<form name="myForm" method="post" action="nonuum_reg.php" onsubmit="validate(event);">
<input name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
<input type="submit" value="Apply" />
</form>
<script>
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == "" || isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12) {
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;
}
}
</script>
You should still create validation on your PHP controller to prevent if users turn off javascript on theirs browser.
Try adding a return true in you =r else close
...
else{
// Put extra check for data format
var ret = validateNum();
if( ret == false )
{
return false;
}
return true;
}
...
This should also help you (not the same issue but same code)link:
<form>
<fieldset>
Password: <span id="capsalert">CAPS LOCK = on</span><br>
<input type="password" id="pwd">
<script type="text/javascript">
document.write(
'<input type="checkbox" name="masking" onclick="unmask(this.checked)"> ' +
'Show the password as I type'
);
</script>
<br>
Password2:<br>
<input type="password" id="pwd2">
</fieldset>
</form>
<script type="text/javascript">
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !!(ev.modifiers & 4) : false));
if(
(kc >= 97 && kc <= 122 && sk) ||
(kc >= 65 && kc <= 90 && !sk)
) {
document.getElementById('capsalert').style.display = 'inline';
}
else {
document.getElementById('capsalert').style.display = 'none';
}//end if
}//end function
function unmask(truefalse) {
oldElem = document.getElementById('pwd');
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById('pwd').value);
elem.id = 'pwd';
oldElem.parentNode.replaceChild(elem,oldElem);
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
}//end function
document.getElementById('pwd').onkeypress = function(e) { chkCaps(e); };
</script>
I'm using the above code in a slightly more complex form.
I have two separate "password" fields on the form. With the current code I can have the first password field show the characters as they are typed when the checkbox is ticked.
Also, the code notifies the user if they are typing with CAPS Lock enabled.
I would like to have both password fields exhibiting the same behavior rather than the first field only. Unfortunately, I do not know how to make that happen.
Thanks for the help.
EDIT:
A simple solution might be easier to find with the following code. I'm willing to use either one.
<script>
function changeType()
{
document.myform.pass.type=(document.myform.option.value=(document.myform.option.value==1)?'-1':'1')=='1'?'password':'text';
}
</script>
<body>
<form name="myform">
<input type="password" name="pass" />
<input type="password" name="pass2" />
<input type="checkbox" name="option" value='1' onchange="changeType()" />
</form>
</body>
Why don't you just change the type attribute of the password inputs in your unmask() function? That way it will be easier for you to manage more than 1 field. After checking whether you have to turn the input into a text one or a password one, do this:
// Suppose 'new_type' is either 'text' or 'password'
// and that 'pwd' and 'pwd2' are the id attributes for
// both of your password fields
document.getElementById('pwd').type = new_type;
document.getElementById('pwd2').type = new_type;
I suggest changing your approach a bit.
You could modify the client with no impact to the server code. For example, I would try using 2 input boxes with the same name. If you ever have one box visible while the other one has the 'disabled' HTML attribute set, the visible box will always be the only one submitted.
This way, your server-side code would only have to look for 1 input, under a single name.
jQuery caps lock test/function?
set both fields to class of password and:
jQuery('.password').caps(function(caps){
if(jQuery.browser.safari) return; // Safari already indicates caps lock
// "this" is current element
if(caps){
alert('Your caps lock is on!');
}else{
// no caps lock on
}
});
Try this:
function chkCaps(e) {
ev = (e ? e : window.event);
kc = (ev.which ? ev.which : (ev.keyCode ? ev.keyCode : false));
sk = (ev.shiftKey ? ev.shiftKey : (ev.modifiers ? !! (ev.modifiers & 4) : false));
if ((kc >= 97 && kc <= 122 && sk) || (kc >= 65 && kc <= 90 && !sk)) {
document.getElementById('capsalert').style.display = 'inline';
} else {
document.getElementById('capsalert').style.display = 'none';
}
//end if
}
//end function
function unmask(truefalse) {
for (var f in new Array('pwd', 'pwd2')) {
oldElem = document.getElementById(f);
elem = document.createElement('input');
elem.setAttribute('type', (truefalse == true ? 'text' : 'password'));
elem.setAttribute('value', document.getElementById(f).value);
elem.id = f;
oldElem.parentNode.replaceChild(elem, oldElem);
document.getElementById(f).onkeypress = function (e) {
chkCaps(e);
};
}
}
//end function
document.getElementById('pwd').onkeypress = function (e) {
chkCaps(e);
};
document.getElementById('pwd2').onkeypress = function (e) {
chkCaps(e);
};
What this does is make it so your code works on pwd and pwd2 by repeating it for each element in the array new Array('pwd', 'pwd2').
Most of the answers didn't work. One or two I left untried because they meant greater changes to my code than I wanted. I ended up finding yet another method to reveal the passwords: "Show password as text" control
I adapted the method there to my multiple password fields scenario:
<input type="checkbox" onchange="document.getElementById('gpwd').type = this.checked ? 'text' : 'password'; document.getElementById('pwd1').type = this.checked ? 'text' : 'password'; document.getElementById('pwd2').type = this.checked ? 'text' : 'password'"> Reveal passwords