how to validate dynamic text box values in jquery - javascript

Thanks in advance.I have a popup window which has a dynamic text box fields.These textboxes will multiple according to the selected combo box values from the first form.The dynamic textboxes are displayed from jquery. Please anyone help me how to validate a dynamic text boxes on clicking the submit button. Actually I have to validate the textboxes before sending the mail. I have written a code which will validate only static textboxes. My code as below
<head>
<script>
$(document).ready(function () {
$(".myformid").click(function(){
var nameVal = $('.names').val();
var emailVal = $('.emails').val();
var phoneVal = $('.phones').val();
if(nameVal == "")
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Name</p>");
}
else if(emailVal == ""){
//alert("A textbox is required");
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the email Id</p>");
}
else if(!ValidateEmail(emailVal))
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Invalid Email Id</p>");
}
else if(phoneVal == "")
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Phone Number</p>");
}
else if(isNaN(phoneVal))
{
$('#errmsg').html("<p style='color:red;font-weight:bold'>Please enter the Valid Phone Number</p>");
}
else if(emailVal !="" && phoneVal != "")
{
$('#errmsg').text(" ");
var username = $('#usernameId').val();
var length = $('#lengthId').val();
var nameArray = [];
var emailArray = [];
var phoneArray = [];
$('.names').each(function(){
nameArray.push(this.value);
});
var nameboxVal = nameArray.join(",");
//alert(nameboxVal);
$('.emails').each(function(){
emailArray.push(this.value);
});
var emailboxVal = emailArray.join(",");
//alert(emailboxVal);
$('.phones').each(function(){
phoneArray.push(this.value);
});
var phoneboxVal = phoneArray.join(",");
//alert(phoneboxVal);
$.ajax({
type: "POST",
url: "/invl_exams/popSubmit",
data: {user:username,name:nameboxVal,email:emailboxVal,phone:phoneboxVal,lengths:length},
success: function(result){
console.log(result);
$('#mailSuccess').text('Mail Send Successfully');
$('#mailSuccess').fadeOut(5000);
}
});
}
});
});
// Passing dynamic textboxes inside the dialog box
$(".create-user").change(function(){
var selVal = $(this).val();
$('#lengthId').val(selVal);
$("#textboxDiv").html('');
if(selVal > 0) {
for(var i = 1; i<= selVal; i++) {
var sno = i;
$("#textboxDiv").append('<tr><td>'+sno+'. </td><td>Name:<input type="text" name="names" class="names" value="" required="required" /></td><td> </td><td>Email:<input type="email" name="emails" class="emails" value="" required="required" /></td><td> </td><td>Phone:<input type="text" name="phones" class="phones" value="" required="required" minlength="10" maxlength="16"/><br/></td></tr>');
}
}
});
});
</script>
</head>
<body>
<div id="dialog" title="Enter details to send Mail">
<!--<form id="myformid" method="post" action="<?php //echo $this->webroot?>users/sendmail">-->
<div id="mailSuccess" style="color:#019002;font-weight:bold"></div>
<form id="myformid" method="post">
<table id="examtable">
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<div id="textboxDiv"></div>
<input type="hidden" name="username" id="usernameId" value="<?php echo $this->Session->read('Auth.User.username'); ?>">
<input type="hidden" name="length" id="lengthId" value="">
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>
<!--<input type="submit" name="btnSubmit" value="Submit">-->
<input type="button" name="btnSubmit" value="Send Mail" id="popSubmit">
</td>
</tr>
</table>
</form>
</div>
</div>
</body>

I don't think any validation is happening at all, whether the elements are static or dynamic.
$(".myformid").click(function(){
will not bind to anything because there are no elements with the class "myformid". The "." at the start of a selector indicates a class.
However you do have an element with an id "myformid". If you change your selector from . to # to indicate an id, then it will bind the event to the form. However, "click" is not the correct event to bind to a <form> element. You want to handle the form's "submit" event:
$("#myformid").submit(function(event){
Lastly, as it stands, your form will do a regular (non-ajax) postback as well as running your function, because the default behaviour of the submit event is not suppressed. Add this line as the first line of the above function:
event.preventDefault();
This will stop a regular postback from happening and allow your validation function to execute. At that point you should have a working solution, assuming the logic in your validation code is what you want.

If your validations are right you just need to attach event in way that dinamicly created elements will be supported too (jQuery on)
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
for example
from
$(".myformid").click(function(){/*Some action*/});
to
$("body").on('click', ".myformid", function(){/*Some action*/});
from
$(".create-user").change(function(){/*Some action*/});
to
$("body").on('change', ".create-user", function(){/*Some action*/});
Small advice: Try to avoid using $("body") selector you can see what is your good dom element witch is parent to your dynamically generated contend/elements.

Related

javascript stop button onClick from submitting form

I have two button inside a form that I don't want to submit the form but add and remove table rows. One button is dynamically added.
I have tried many ways to prevent the submission but none seem to work. When I was getting the button by id and using an event listener it was ok but that did not work with button that get added after age load. I am trying to find a solution that will work with buttons. The one that loaded on page load and the ones that get added dynamically with JavaScript.
<table id="conditions-table">
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th></th>
</tr>
<tr>
<td>
<input id="condtitions-input"></input>
<select id="condtitions-level">
<option value="Mandatory">Mandatory</option>
<option value="Important">Important</option>
<option value="Support">Support</option>
</select>
</td>
<td>
<button id="add-condtition" onclick="addCondition(e); return false;">Add Conditions</button></td>
</td>
</tr>
</thead>
</table>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
<script>
var counter = 0;
function addCondition(e){
e.preventDefault()
var table = document.getElementById("conditions-table");
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var condtionsInput = document.getElementById("condtitions-input");
var condtionsInputValue = condtionsInput.value;
condtionsInput.value = "";
var selectedLevel = document.getElementById("condtitions-level");
var selectedLevelValue = selectedLevel.value;
cell1.innerHTML = `<input type="text" name="strategies_conditions[${counter}][name]" value=" ${condtionsInputValue}"></input>
<select>
<option ${(selectedLevelValue == "Mandatory") ? 'selected="selected"' : ""} value="Mandatory">Mandatory</option>
<option ${(selectedLevelValue == "Important") ? 'selected="selected"' : ""} value="Important">Important</option>
<option ${(selectedLevelValue == "Support") ? 'selected="selected"' : ""} value="Support">Support</option>
</select>`;
cell2.innerHTML = "<button class='remove-condition' onclick="removeCondition()">X</button></td>";
counter++;
return false;
};
function removeCondition() {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
};
The default type of a button is "submit"; just override that behavior by setting it to "button".
cell2.innerHTML = "<button type='button' class='remove-condition' onclick='removeCondition()'>X</button></td>";
You also need to define event as a parameter of the event handler function.
function removeCondition(event) {
// event.target will be the input element.
var td = event.target.parentNode;
var tr = td.parentNode; // the row to be removed
tr.parentNode.removeChild(tr);
};
Just don't insert the argument e inside the onclick event in the markup you can apply an event using JavaScript like the following
btn.onclick = e => {
e.preventDefault();
}
<form>
<input type="text" name="" placeholder="Name">
<input type="submit" name="" id="btn">
</form>
or you can simply make a onclick event return false like the following
<form>
<input type="text" name="" placeholder="Name">
<input type="submit" name="" id="btn" onclick="return false">
</form>
to add an event to an element that doesn't exist yet on the DOM you need to know about event.target
here is a sample that might help you
document.addEventListener( "click", listenerFunction );
function listenerFunction(event){
var element = event.target;
// here you check for that auto generated element
if(element.tagName == 'A' && element.classList.contains("someBtn")){
console.log("hi");
}
}
All you really need to do is add:
<input type="submit" onclick="event.preventDefault();">
You probably want to handle it though so in total you'd probably do something more like this:
<script>
function myFunction(){
if (confirm("Are you sure you want to ...? This action cannot be undone.")) {
document.getElementById("myForm").submit();
}
}
</script>
<form method="post" action="/test" id="myForm">
<input type="submit" onclick="event.preventDefault();myFunction();">
</form>
This allows the user to click ok to proceed or cancel to not have it submit the form.

JS validation troubles and some more gimmicks

I've already have validated my form using php but I would like to change it to use javascript.For some reason it doesn't seem to work, and I cannot understand why.
<form name="adminFormNewMember" method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>>
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter()" required autofocus></td>
</tr>
</table>
</form>
---------------------
<script>
function allLetter()
{
var text = document.getElementById("firstname");
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
return true;
}
else
{
alert("message");
return false;
}
}
</script>
Obviously the form contains more stuff, I've omitted them for the sake of clarity.
Also I'd like to use the same function for more field such as lastname etc, but I don't know how to do that since I'm using the getElementById
Finally, I'd like to just highlight the textfield red for errors, green for correct etc.
Clarification Edit I still need the PHP part I just don't want it to validate. I need the validation to happen for each field onBlur, and then the data to be passed to the php function to be inserted in a DB etc.
Try this :
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<form name="adminFormNewMember" method="post" >
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter(this.id)" required autofocus></td>
</tr>
</table>
</form>
<script>
var allLetter = function(id){
var text = document.getElementById(id).value;
if(text.length ==0 || text.toUpperCase().replace(/[^A-Z]/g, "").length != text.length) alert("Incorrect value")
}
</script>
</body>
</html>
To use your function with several fields, just pass the id as a parameter (this.id), in allLetters function, pass the parameter to getElementById.
It seems your Regexp is not correct (or suffiscient), so first check the field is not empty then check if length of value equals lenngth of value with letters only. If so the field is correct, otherwise go for the alert.
Maybe you should consider using jquery and the validate plugin here witch can save you lot of time
Returning true or false in your sample code is achieving nothing. What you need to do is, depending on whether validation is successful or not, add a CSS class to your input field. This CSS class should handle either background or border for your field to indicate that it did not match the criteria.
Instead of using onblur attribute, create an event listener for the blur event on your form fields. Delegate this listener to transfer control to a function which will take the value inside the event target and validate it. This should make your code more modular and apply to most fields.
Here is some code in basic javascript:
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" class="formFields"></td>
<td>Last Name </td>
<td><input type="text" id="lastname" class="formFields"></td>
<td>Fathers Name</td>
<td><input type="text" id="fathername" class="formFields"></td>
</tr>
<script>
for(var i=0; i < document.getElementsByClassName("formFields").length ; i++){
document.getElementsByClassName("formFields")[i].addEventListener("blur", function(evt){
var text = evt.target;
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
evt.target.classList.remove('incorrectField');
evt.target.classList.add('correctField');
}
else
{
evt.target.classList.add('incorrectField');
evt.target.classList.remove('correctField');
}
});
}
<style>
.incorrectField{
background: red;
}
.correctField{
background: green;
}
</style>

Can't use JQuery form validation with two buttons html form

HTML:
<form id="myForm">
<fieldset>
<ol>
<li>
<label for="data">Data</label>
<input id="data" name="data" type="text" placeholder="Ex.º: 14-02-2014" required>
</li>
<li>
<label for="conta">Conta</label>
<input id="conta" type="text" name="conta" placeholder="Ex.º: " required>
</li>
</ol>
<input id="oknovo" type="submit" value="OK & Novo" />
<input id="okfechar" type="submit" value="OK & Fechar" />
</fieldset>
</form>
JS:
$(document).ready(function () {
var form = $('#myForm');
var botao;
form.validate();
if (form.valid()) {
$("#myForm input[type=submit]").click(function (event) {
botao = $(this).attr('id');
alert("clique " + botao);
});
};
});
I want to validate the form using JQuery validation plugin.
If it is valid according to the rules specified in the HTML form, then identify which of the buttons was clicked. The validation plugin is working but the form is never valid, therefore the function is never called to alert the id of the button.
You may see a live JSFiddle here.
If the form isn't valid at DOM ready (which it will never be), then your code to add the event handler to the button won't run. You should consider running your validation on a different event, say when the text in the textbox changes.
Example:
$('input[type=textbox]').change(function() {
// put your validation code here.
});
Put your validation inside the click event, and it starts working:
$(document).ready(function () {
var form = $('#myForm');
var botao;
form.validate();
$("#myForm input[type=submit]").click(function (event) {
if (form.valid()) {
botao = $(this).attr('id');
alert("clique " + botao);
}
event.preventDefault();
});
});
Working fiddle
Try adding event.preventDefault();
$("#myForm input[type=submit]").click(function (event) {
event.preventDefault();
botao = $(this).attr('id');
alert("clique " + botao);
});

Post Dynamic Inputs that are Appended with jQuery

I have found multiple questions that are the same, these include:
dynamically inserted form inputs aren't posted
jQuery not posting all inputs of a form after the .append()
Most problems are caused by opening the form within a table / div or some other problem with the HTML. I don't believe I have either of these problems; I suspect my javascript needs to be tweaked.
I am using jQuery as so:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
When the add link is clicked a new table row is appended to tbody.newRow
When clicking .remove, you are asked for confirmation. Upon confirmation the row is removed.
The form is submitted via ajax when input.Value loses focus.
jQuery:
$(document).ready(function() {
$(".add").on('click', function() {
$("tbody.newRow").append(
'<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection">Remove</td></tr>'
);
});
$("tbody").on('click', '.remove', function() {
$(this).parent().append($(
'<div class="confirmation">YesNo</div>'
))
$(this).remove();
});
$("tbody").on('click', '.removeConfirm', function() {
$(this).parent().parent().parent().remove();
});
$("tbody").on('click', '.removeCancel', function() {
$(this).parent().parent().append(
'Remove');
$(this).parent().remove();
});
var formTwo = $('.ajaxTwo'); // contact form
// form submit event
$(".Value").blur(function() {
$.ajax({
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formTwo.serialize(), // serialize form data
success: function(data) {
url: 'functions.php'; // form action url
},
error: function(e) {
console.log(e)
}
});
});
});
The html form. The ajax works wonderfully with the existing row that is not added dynamically. The add row is located in the table footer looking pretty. The form is posted as an array.
<form class="ajaxTwo" method="post">
<table>
<tbody class="newRow">
<tr>
<td>
<input type="text" name="NewJobLeviesId[]" class="JobLeviesId" />
<input type="text" name="NewValue[]" class="Value" />
<input type="text" name="MasterId[]" class="Values" />
<input type="text" name="LUPChoiceId[]" class="Values" />
<input type="text" name="SortOrder[]" class="Values" />
</td>
<td class="removeSelection">
Remove
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
Add Row
</td>
</tr>
</tfoot>
</table>
</form>
Finally the php. Each row is inserted into my database table with a PDO prepared statement.
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
if(isset($_POST['NewJobLeviesId'])) {
for($i=0; $i<count($_POST['NewJobLeviesId']); $i++) {
$NewJobLeviesId = $_POST['NewJobLeviesId'][$i];
$NewValue = $_POST['NewValue'][$i];
$MasterId = $_POST['MasterId'][$i];
$LUPChoiceId = $_POST['LUPChoiceId'][$i];
$SortOrder = $_POST['SortOrder'][$i];
$sql = "INSERT INTO joblevies (JobLeviesId,Value,MasterId,LUPChoiceId,SortOrder) VALUES (:JobLeviesId,:Value,:MasterId,:LUPChoiceId,:SortOrder)";
$q = $db->prepare($sql);
$q->execute(array(':JobLeviesId'=>($NewJobLeviesId),':Value'=>($NewValue),':MasterId'=>($MasterId),':LUPChoiceId'=>($LUPChoiceId),':SortOrder'=>($SortOrder)));
}
}
}
Again, this works wonderfully well. Only the dynamically added inputs have a problem. What am I missing?
The dynamically created dom elements don't have any of the events that you attach on $(document).ready(... because they didn't yet exist when you were attaching events. So the $('.Value').blur(... stuff is only attached to the first form, and not any future ones. So attach the event every time you create a new row, so maybe something like this:
First, delegate the binding action to its own function
function attachSubmitEvent() {
// form submit event
//remove old events first
$(".Value").off();
$(".Value").blur(function () {
var formTwo = $('.ajaxTwo'); // contact form
$.ajax({
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formTwo.serialize(), // serialize form data
success: function (data) {
url: 'functions.php'; // form action url
},
error: function (e) {
console.log(e)
}
});
});
}
then in your document.ready, call that function
attachSubmitEvent();
then, to make sure they are also attached to the new elements, call it again when creating new elements
$(".add").on('click', function () {
$("tbody.newRow").append('<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection">Remove</td></tr>');
attachSubmitEvent(); //now everyone has the event attached.
});
For your form submit event, try:
$("tbody").on('focusout', '.Value', function() {
...
});
You could also use blur in this event handler, but the documentation recommends using focusout for clarity (See 'Additional Notes' section of jQuery on() method documentation: http://api.jquery.com/on/)

How to get siblings in different DIVs or SPANs?

I have a number of forms on a page, like this:
<form>
<input type="hidden" name="id" value="someID1">
<div>
<span>
<input type="submit" class="submitClass">
</span>
</div>
<div>
<input type="text" name="name" class="someClass" value="name1">
</div>
</form>
<form>
<input type="hidden" name="id" value="someID1">
<div>
<span>
<input type="submit" class="submitClass">
</span>
</div>
<div>
<input type="text" name="name" class="someClass" value="name1">
</div>
</form>
Then I have some JS:
jQuery(document).ready(
function()
{
console.log("page loaded");
jQuery(".submitClass").on("click", function() {
var id = jQuery(this).siblings("input[name='id']").val();
var name = jQuery(this).siblings("input[name='name']").val();
console.log(id);
console.log(name);
return false;
});
}
);
JSFIDDLE: http://jsfiddle.net/sEXg3/
When the submit button is clicked, I want to stop the form from being submitted and get the values of the two inputs I have next to the submit button.
I tried doing this with the .siblings() function, but it doesn't work since the inputs are in different DIVs/SPANs (if I put them all right next to each other, it does work).
How can I accomplish this?
The elements you are looking for are not the sibling of the submit button.
In your case I would suggest to find the form element (you can find the form element in which the clicked button is present using .closest()) and them find the desired inputs fields inside it using .find()
jQuery(function ($) {
console.log("page loaded");
$(".submitClass").on("click", function () {
var $this = $(this),
$form = $this.closest('form');
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
console.log(id);
console.log(name);
return false;
});
});
Demo: Fiddle
Since your .submitClass is placed in div and in span it's not a sibling of the other inputs... you can try something like this: (Working jsFiddle)
var id = jQuery(this).closest('form').find("input[name='id']").val();
var name = jQuery(this).closest('form').find("input[name='name']").val();
You first look for the parent form, then inside it look for the input fields.. an even more efficient version will be:
var $form = jQuery(this).closest('form');
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();

Categories