I have here a form validation. I used this validation in multiple editing records in php. I have two textbox that comparing it's value. I tried to mix my validation script and comparing value script but isn't working properly.
This what I have now but I'm having problem with this when I tried to input lower value in n_quanity field the validation error message is not working and it allowed the form to submit. I want to display error in span not alert the message. Help please?
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
for (var i = 0,len=textBox1.length; i < len;i++) {
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
return false;
} else {
$(this).next("span.val_qty").html("");
}
}
});
And this is my full code
<script>
jQuery(function($) {
var validation_holder;
$("form#register_form input[name='submit']").click(function() {
var validation_holder = 0;
$('.qty').each(function(){ // use $.each for all project class
qty = this.value;
if(qty == "") {
$(this).next("span.val_qty").html("This field is Required.").addClass('validate');
validation_holder = 1;
} else {
$(this).next("span.val_qty").html("");
}
});
if(validation_holder == 1) { // if have a field is blank, return false
$("p.validate_msg").slideDown("fast");
return false;
} validation_holder = 0; // else return true
/* validation end */
}); // click end
}); // jQuery End
</script>
<script>
$('#sbtBtn').on('click', function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0,len=textBox1.length; i < len;i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
alert('value is greater than quantity');
return false;
} else {}
}
});
</script>
<p> <label for="">PR Quantity</label> <input name="n_quantity[]" id="n_quantity" class="qty n_quantity" type="text"/><span class="val_qty"></span> </p>
<p style="display:none;"><input id="pr_total" class="pr_total" type="text"></p>
Related
So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";
How can I prevent duplicate values being added to a combobox? I also need to prevent the space value. This is my code but its not working.
An entry is entered the first time input but the second time I enter input its alerting me that I have entered a duplicate value even when I enter different values.
Please see this jsFiddle https://jsfiddle.net/adLxoakv/
<HTML>
<HEAD>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<fieldset>
<legend>Combo box</legend>
Add to Combo: <input type="text" name="txtCombo" id="txtCombo"/>
Selected: <input type="text" name="selected" id="selected"/>
IMEI Selected: <input type="text" name="imei" id="imei"/>
<input type="button" id="button" value="Add" onclick="addCombo()">
<br/>
Combobox: <select name="combo" multiple id="combo"></select>
</fieldset>
</BODY>
</HTML>
<script>
$("#txtCombo").on("keydown", function (e) {
return e.which !== 32;
});
$(document).ready(function() {
$('#button').click(function(){
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
var count = $("#combo :selected").length;
$('#selected').val(count);
});
});
$("#combo").on('change', function () {
var count = $("#combo :selected").length;
$('#selected').val(count);
});
var text = $("#text").val();
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
option.text = textb.value;
option.value = textb.value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if (combo.length) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
// separated by comma to textbox
$(document).ready(function() {
$("#combo").change(function() {
var data = [];
$.each($("#combo option:selected"), function() {
data.push($(this).attr("value"));
});
$('#imei').val(data.join(","));;
});
});
</script>
To find the duplicate you can use following function(using jQuery)
function isDuplicate(value,text){
/*Get text of the option identified by given value form the combobox and then check if its text matches the given text*/
if($('#combo select option[value="' + value + '"]').text() == text)
return true;
else
return false;
}
Update:
function addCombo() {
var textb = document.getElementById("txtCombo");
var combo = document.getElementById("combo");
var option = document.createElement("option");
var value = textb.value.trim();
option.text = value;
option.value = value;
option.selected = true;
if (textb.length == 0) {
return false;
}
if ($('#combo option[value="' + value + '"]').text() == value ) {
alert("Duplicate found");
return false;
}
try {
combo.add(option, null ); //Standard
}catch(error) {
combo.add(option); // IE only
}
textb.value = "";
}
let us say we have parameter with A,B,C and D values. Now we want to force the user to choose only A,B,C or A,C,D or A or B or C.
Instead of Allowing all possible 16 combination, we want to allow only 5 predefined combination. I tried it but for this i have to put condition for each and every selection.
If we assume this values are bind with checkbox and we need to check whether selected values are as per our predifined combination or not.
I need to achieve this in javascript or either angular.js. Please help me with proper algorithm for such operation.
I tried below logic to achieve this but this will not infor user instantly, alert only after final submission
// multi-dimentional array of defined combinations
var preDefinedCombinations = [['a','b','c'], ['a','c','d'], ['a'], ['b'], ['c']];
// Combination user select
var selectedvalues = [];
// Function called on selection or removing value (i.e a,b,c,d)
function selectOption(value){
var checkIndex = selectedvalues.indexof(value);
if(checkIndex == -1){
selectedvalues.push(value);
}else{
selectedvalues.splice(checkIndex, 1);
}
}
// function called on submition of combination
function checkVaildCombination(){
if(preDefinedCombinations.indexOf(selectedvalues) == -1){
alert('Invalid Combination');
}else{
alert('Valid Combination');
}
}
This code gives information only about combination is valid or not, not about which may be possible combinations as per selections.
stolen from https://stackoverflow.com/a/1885660/1029988 :
function intersect_safe(a, b)
{
var ai=0, bi=0;
var result = new Array();
while( ai < a.length && bi < b.length )
{
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they're equal */
{
result.push(a[ai]);
ai++;
bi++;
}
}
return result;
}
then in your code:
function checkVaildCombination(){
function get_diff(superset, subset) {
var diff = [];
for (var j = 0; j < superset.length; j++) {
if (subset.indexOf(superset[j]) == -1) { // actual missing bit
diff.push(superset[j]);
}
}
return diff;
}
if(preDefinedCombinations.indexOf(selectedvalues) == -1){
missing_bits = [];
diffed_bits = [];
for (var i = 0; i < preDefinedCombinations.length; i++) {
var intersection = intersect_safe(preDefinedCombinations[i], selectedvalues);
if (intersection.length == selectedvalues.length) { // candidate for valid answer
missing_bits.push(get_diff(preDefinedCombinations[i], intersection));
} else {
var excess_bits = get_diff(selectedvalues, intersection),
missing_bit = get_diff(preDefinedCombinations[i], intersection);
diffed_bits.push({
excess: excess_bits,
missing: missing_bit
});
}
}
var message = 'Invalid Combination, if you select any of these you`ll get a valid combination:\n\n' + missing_bits.toString();
message += '\n\n Alternatively, you can reach a valid combination by deselected some bits and select others:\n';
for (var j = 0; j < diffed_bits.length; j++) {
message += '\ndeselect: ' + diffed_bits[j].excess.toString() + ', select: ' + diffed_bits[j].missing.toString();
}
alert(message);
} else {
alert('Valid Combination');
}
}
you will of course want to format the output string, but that code will (hopefully, it is napkin code after all) give you the missing bits to make valid combos with what you've got selected already
May be following code could help you to solve ur problem
<script>
function validateForm(){
var checkBoxValues = this.a.checked.toString() + this.b.checked.toString() + this.c.checked.toString() + this.d.checked.toString();
if( checkBoxValues == 'truetruetruefalse' || // abc
checkBoxValues == 'truefalsetruetrue' || // acd
checkBoxValues == 'truefalsefalsefalse' || // a
checkBoxValues == 'falsetruefalsefalse' || // b
checkBoxValues == 'falsefalsetruefalse' ){ // c
return true;
}
return false;
}
</script>
<form onsubmit="return validateForm()" action="javascript:alert('valid')">
<input type="checkbox" name="mygroup" id="a">
<input type="checkbox" name="mygroup" id="b">
<input type="checkbox" name="mygroup" id="c">
<input type="checkbox" name="mygroup" id="d">
<input type="submit">
</form>
http://jsfiddle.net/R89fn/9/
If any of the text input/Box added are empty then the page must not submit.when I try to retrieve values from the text inputs using their id`s nothing gets retrieved is it possible to retrieve values from elements added dynamically?
$("#submit").click(function (event) {
var string = "tb";
var i;
for (i = 1; i <= count; i++) {
if (document.getElementById(string+1).value=="") {
event.preventDefault();
break;
}
}
});
The above code is what I am using to get the value from the text fields using there id
I took a look on the code in the JSFiddle. It appears that the input textboxes are not given the intended IDs; the IDs are given to the container div.
The code for the add button should use this,
var inputBox = $('<input type="text" id="td1">') //add also the needed attributes
$(containerDiv).append(inputBox);
Check out this solution on fiddle: http://jsfiddle.net/R89fn/15/
var count = 0;
$(document).ready(function () {
$("#b1").click(function () {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$('#form').append("<div class=\"newTextBox\" id=" + tb + ">" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function () {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function (event) {
var inputBoxes = $('#form').find('input[type="text"]');;
if (inputBoxes.length < 1) {
alert('No text inputs to submit');
return false;
} else {
inputBoxes.each(function(i, v) {
if ($(this).val() == "") {
alert('Input number ' + (i + 1) + ' is empty');
$(this).css('border-color', 'red');
}
});
alert('continue here');
return false;
}
});
});
<form name="form" id="form" action="htmlpage.html" method="POST">
<input type="button" id="b1" name="b1" value="Add TextBox" />
<input type="button" id="b2" name="b2" value="Remove TextBox" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script>
var count = 0;
$(document).ready(function() {
$("#b1").click(function() {
if (count == 5) {
alert("Maximum Number of Input Boxes Added");
} else {
++count;
var tb = "tb" + count;
$(this).before("<div class=\"newTextBox\" id= "+ tb +" >" + 'InputField : <input type="text" name="box[]"></div>');
}
});
$("#b2").click(function() {
if (count == 0) {
alert("No More TextBoxes to Remove");
} else {
$("#tb" + count).remove();
--count;
}
});
$("#submit").click(function(event) {
var string = "#texttb";
var i;
for (i = 1; i <= count; i++) {
if ($('input[type = text]').val() == "") {
event.preventDefault();
break;
}
}
});
});
</script>
<style>
.newTextBox
{
margin: 5px;z
}
</style>
Reason:
you had given id to the div element. so its not get retrive. i had updated the answer with the usage of jquery functions and changed your code for this requirement.
If I understand correctly, your only issue atm is to make sure that the form is not sent if one of the inputs are empty? Seems the solution to your problem is simpler. Simply add required at the end of any input and HTML5 will ensure that the form is not sent if empty. For example:
<input type="text" required />
This has me pulling my hair out. Button on site has onclick=method() and it's not calling the method. The method is supposed to grab all the checkboxes, check their checked state and fill the chk[] array with true/false. The WebMethod then takes that array, breaks it down into three smaller arrays and runs checks on the combinations. So far as I can tell, the button never calls the method to begin with.
aspx page:
<fieldset id="Fieldset">
<button onclick="SendForm();">Send</button>
<button onclick="CancelForm();">Cancel</button>
</fieldset>
</form>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
var chk = new [42];
for (i = 0; i < elLength; i++) {
var count = 0;
var type = form1.elements[i].type;
if (type == "checkbox") {
if (form1.elements[i].checked) {
chk[count] = true;
}
else {
chk[count] = false;
}
count++;
}
else {
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>
codebehind method it's calling:
[WebMethod]
public static void SendForm(string email, bool[] chk)
{
bool[] desc = new bool[14];
bool[] loc = new bool[14];
bool[] other = new bool[14];
for (int i = 0; i < 14; i++)
{
int count = i * 3;
desc[i] = chk[count];
loc[i] = chk[count + 1];
other[i] = chk[count + 2];
}
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
for (int i = 0; i < 14; i++)
{
if (desc[i])
{
if ((loc[i]) && (other[i]))
{
throw new Exception("Invalid, two parameters selected");
}
else if (loc[i])
{
// do stuff
}
else if (other[i])
{
// do stuff
}
else
{
throw new Exception("Invalid, every exemption must have at least one reason selected");
}
}
else
{
throw new Exception("No exemptions have been selected");
}
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
EDIT!!:
Running the page with the following script instead of the previous script works like a charm. No clue why the previous didn't work.
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
for (i=0;i< elLength;i++) {
var type = form1.elements[i].type;
if (type == "checkbox" && form1.elements[i].checked) {
alert("true!");
}
else {
alert("false!");
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>
Instead of calling your function like
<button onclick="SendForm();">Send</button>
try calling it like this
<button onclick="javascript:return SendForm();">Send</button>
Running the page with the following script instead of the previous script works like a charm. No clue why the previous didn't work.
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
var elLength = form1.elements.length;
for (i=0;i< elLength;i++) {
var type = form1.elements[i].type;
if (type == "checkbox" && form1.elements[i].checked) {
alert("true!");
}
else {
alert("false!");
}
}
PageMethods.SendForm(email, chk, OnSucceeded, OnFailed);
}
</script>