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>
Related
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
}
})
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
This one continues to throw me for a loop...only in Chrome is this happening.
I have an "upgrade page" where a user can click a plan and then go to a form. I pass the ?plan=# here and then make it select the option that fits. For some reason, in Chrome, it IS selecting it as it shows in inspect element...however, it does not display in the select box.
I am trying a bunch of different ways to make this work in chrome, with jquery, php, html, anything I can think of, but nothing seems to be working.
Here is the jquery code:
$(document).ready(function() {
var split = location.search.replace('?', '').split('=')
var getPlan = split[1];
console.log(getPlan);
if (getPlan == 1) {
$("#memberPlan").val('premium');
} else {
$("#memberPlan").val('vip');
}
function vip() {
var list = "";
list = "<option value=\"3\">VIP: per month ($9.00)</option>\n";
list += "<option value=\"4\">VIP: every 6 months ($47.00)</option>\n";
list += "<option value=\"5\">VIP: per year ($89.00)</option>\n";
$("#service").html(list);
}
function premium() {
var list = "";
list = "<option value=\"0\">Premium: per month ($5.00)</option>\n";
list += "<option value=\"1\">Premium: every 6 months ($27.00)</option>\n";
list += "<option value=\"2\">Premium: per year ($49.00)</option>\n";
$("#service").html(list);
}
var currentPlan = $("#currentPlan").text().toLowerCase();
$('#memberPlan').attr("value", currentPlan);
if ($("#memberPlan").val() == "premium") {
premium();
}
if ($("#memberPlan").val() == "vip") {
vip();
}
$("#memberPlan").change(function() {
if ($("#memberPlan option:selected").val() == 'vip'){
vip();
}
if ($("#memberPlan option:selected").val() == 'premium'){
premium();
}
});
});
and here is the html/php ($payPlan is $_GET['plan']):
<select name="member_plan" id="memberPlan">
<option value="premium"<?php echo $payPlan == 1 ? ' selected':''; ?>>Premium</option>
<option value="vip"<?php echo $payPlan == 2 ? ' selected':''; ?>>VIP</option>
</select>
Thanks in advance, any help is appreciated :)
Try this
$("#memberPlan").change(function() {
if ($(this).val() == 'vip'){
vip();
}
if ($(this).val() == 'premium'){
premium();
}
});
Sometimes I find the "on" handler binds to the element with more consistent behavior. Try?
$("#memberPlan").on('change', function() {
if ($(this).val() == 'vip'){
vip();
}
if ($(this).val() == 'premium'){
premium();
}
});
I'm trying to validate some form fields using JS functions, but they don't seem to load or check the field when the submit button is clicked.
<html>
<body>
<?php require_once('logic.php'); ?>
<h1>Add new Region/Entity</h1>
<?php
if ($_POST['submitted']==1) {
echo $error;
}
?>
<form action="logic.php" method="post" name="registration" onSubmit="return formValidation();">
Region: <input type="text" name="region" value="<?php echo #$_POST['region']; ?>"><br>
Description: <br><textarea name="description" cols="50" rows="10"><?php echo #$_POST['description']; ?></textarea><br>
Remarks: <input type="text" name="remarks" value="<?php echo #$_POST['remarks']; ?>">
<input type="hidden" name="submitted" value="1"><br>
<input type="submit" value="Submit" onclick="">
And here's the JS:
<script type="text/javascript">
function formValidation() {
var region = document.registration.region;
var descr = document.registration.description;
var remarks = document.registration.remarks;
if(empty_validation()) {
if(reg_validation()) {
if(reg_letters()) {
if (desc_letters()) {
if (desc_validation()) {
}
}
}
}
}
return false;
}
function empty_validation() {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
function reg_validation() {
if (reg_len > 50) {
alert("Only 50 characters are allowed in the Region field");
region.focus();
return false;
}
return true;
}
function reg_letters() {
var letters = /^[A-Za-z]+$/;
if(region.value.match(letters)) {
return true;
} else {
alert('Region field must have only alphabetical characters');
region.focus();
return false;
}
}
function desc_validation() {
if (descr_len > 500) {
alert("Only 500 characters are allowed in the description field");
descr.focus();
return false;
}
return true;
}
function desc_letters() {
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < descr_len; i++) {
if (iChars.indexOf(descr.value.charAt(i)) != -1) {
alert ("Your description has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
return true;
}
</script>
</form>
</body>
</html>
As you can see, I'm posting values from the form to a PHP file. And I've used the onSubmit event in the form tag to initialize the formValidation() function. It isn't working for some reason.
Here's a working example if you need one.
I'm not going to fix every little error you have, but the main problem is that variables aren't defined where you expect them to be. You can't declare a variable in one function and expect it to be available in the next (without passing it as a parameter or declaring it globally). For example, your empty_validation function should be this:
function empty_validation(region, descr, remarks) {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
And in your formValidation function, you call it like this:
if(empty_validation(region, descr, remarks)) {
This is just one example, and you would need to do it in a few places.
A few other things - you always return false from formValidation...did you mean to put return true; inside the innermost if statement? Also, since all you seem to be doing is calling each of those functions, you can probably put them into one big if statement, like this:
if (empty_validation() && reg_validation() && reg_letters() && desc_letters() && desc_validation()) {
return true;
}
return false;
I have a page that lets people assign items to a category and javascript that lets user move as many items as desired from one box on left to one on right and back so that users can preview and fine tune choices (which end up in right box). It might be better if the items could be moved between lists instead of listboxes, but select box, I guess, is good for selecting uponclick. When user is done, I need to post items in right box to php script. However, am having trouble figuring out how to capture all the items in the right list. There is no form in the script so can't get it from document.form. Items are not really selected, they just populate list and I want to get them all. Is there a variable that has the whole list? Script is lengthy so here are functions that do work. Essentially I need a way to write out list of elements in right box at end. Thanks for any suggestions.
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {
if (listLeft.options.length == 0) {
alert('You have already assigned all items to the category');
return false;
} else {
var selectedItem = listLeft.options.selectedIndex;
move(listRight, listLeft.options[selectedItem].value, listLeft.options[selectedItem].text);
listLeft.remove(selectedItem);
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
} else if (side == 2) {
if (listRight.options.length == 0) {
alert('The list is empty');
return false;
} else {
var selectedItem = listRight.options.selectedIndex;
move(listLeft, listRight.options[selectedItem].value, listRight.options[selectedItem].text);
listRight.remove(selectedItem);
if (listRight.options.length > 0) {
listRight.options[0].selected = true;
}
}
}
}
function move(listBoxTo, optionValue, optionDisplayText) {
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
First, I think you have an error in your syntax. To get the value of the selected item of a select box, you would use something like:
var value = listLeft.options[listLeft.selectedIndex].value;
To write out all the options in a particular select box, you should be able to do something like this:
var options = document.getElementById('selectRight').options;
for (i=0; i<options.length(); i++)
document.write("value "+ i +" = "+ options[i].value);
I reworked your code a tiny bit and here is a complete working example:
<html>
<head>
<style type="text/css">
select
{
width:100px;
}
</style>
<script type="text/Javascript">
function moveToRightOrLeft(side)
{
if (side == 1)
{
var list1 = document.getElementById('selectLeft');
var list2 = document.getElementById('selectRight');
}
else
{
var list1 = document.getElementById('selectRight');
var list2 = document.getElementById('selectLeft');
}
if (list1.options.length == 0)
{
alert('The list is empty');
return false;
}
else
{
var selectedItem = list1.options[list1.selectedIndex];
move(list2, selectedItem.value, selectedItem.text);
list1.remove(list1.selectedIndex);
if (list1.options.length > 0)
list1.options[0].selected = true;
}
return true;
}
function move(listBoxTo, optionValue, optionDisplayText)
{
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
function showContents(listBoxID)
{
var options = document.getElementById(listBoxID).options;
for (var i = 0; i < options.length; i++)
alert("Option "+ options[i].value +" = "+ options[i].text);
}
</script>
</head>
<body>
<select id="selectLeft" multiple="multiple">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<button onclick="moveToRightOrLeft(2)"><</button>
<button onclick="moveToRightOrLeft(1)">></button>
<select id="selectRight" multiple="multiple">
</select>
<button onclick="showContents('selectRight')">Show Contents</button>
</body>
</html>