Dynamically add html depending on dynamically generated html with jQuery - javascript

I'm currently working on a project for which I have to develop a WordPress plugin allowing to manipulate tables in databases. My work is based on this plugin, which I'm improving and editing to match the requirements of my company : https://wordpress.org/plugins/create-db-tables/
My problem however doesn't concern MySQL, but html, Php and jQuery (especially jQuery, which I'm not familiar with, at all). It's about dynamically generating a form, itself depending on a dynamically generated form (yeah...).
With the following code, the plugin user is able to dynamically add rows to the table he's creating. I would like him to be able to add "sub-rows" (I know how to handle it server-side, my problem here is only the interface), like that :
http://i.imgur.com/XHwI54W.png
When the user clicks "Add subrows", a zone appears where he can fill out a form, etc. It works perfectly (at least the interface) for the first row, but after that, whenever I click another "Add subrows" button, nothing happens.
I'd appreciate very much if someone could take time to tell me where I'm doing something wrong. Thank you so much ! :)
Here is my code :
(the first jQuery script seemingly works, I'm not the one who developed it. I duplicated it and tried to adapt the second one to my "sub-row" requirement)
<form id="create-table" method="post" action="<?php echo admin_url('admin-post.php'); ?>">
<input type="hidden" name="action" value="add_table">
<fieldset class="table-fieldset">
<label id="table-name">Table Name:</label> <br />
<span style="position: relative; top: 2px;"><?php echo "Choose prefix (by default wp_ ) : " ?></span><input type="text" class="prefix-name" name="prefix_name" size="4" id="prefix-name"><br />
<span style="position: relative; top: 2px;"><?php echo "Choose table name :" ?></span><input type="text" class="table-name" name="table_name" size="30" id="table-name">
<span>(Alphanumeric only, no special characters.)</span> <br/> <br/>
<span><font color="blue"><strong>Will this table be used for user authentication ? </strong></font></span><input type="checkbox" class="is-user-auth" name="is_user_auth" id="is-user-auth"><br/>
<span><strong>/!\ Only one table at a time can be used for user authentication : if a current table is used for this purpose, it won't be anymore.</strong></span><br/><br/>
</fieldset>
<div id="rows">
<fieldset class="row-fieldset" id="row-fieldset" value="1"><label id="row-label">Row:</label><input type="text" class="name-input" name="name[]" placeholder="Name" size="20"><input type="text" class="type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20"><span id="null-label">Null</span><input type="checkbox" class="null-input" name="null[]"><input type="text" class="default-input" name="default[]" placeholder="Default Value" size="20"><span id="unique-label">Unique</span><input type="checkbox" class="unique-input" name="unique[]"><button type="button" class="row-dynamic" style="background-color: #E3F6CE">Add subrows</button><div id="subrows1" value="1"></div></fieldset>
</div>
<div id="add-row">
<button type="button" class="add-row button-secondary">Add Row</button>
</div>
<fieldset>
<input type="hidden" id="items" name="items" value="1" />
</fieldset>
<fieldset>
<input type="hidden" id="subrowitems" name="subrowitems" value="101" />
</fieldset>
<fieldset>
<button type="submit" class="button button-primary button-large">Create Table</button>
</fieldset>
</form>
<!-- Script to add rows -->
<script>
jQuery(function($) {
$('.add-row').click(function () {
$('#items').val(function(i, val) { return +val+1 });
var val_2=$('#items').attr('value');
var subrow_name = 'subrows'+val_2;
var rowHTML = '<fieldset class="row-fieldset" id="row-fieldset" value=\"'+val_2+'\"><label id="row-label">Row:</label><input type="text" class="name-input" name="name[]" placeholder="Name" size="20"><input type="text" class="type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20"><span id="null-label">Null</span><input type="checkbox" class="null-input" name="null[]"><input type="text" class="default-input" name="default[]" placeholder="Default Value" size="20"><span id="unique-label">Unique</span><input type="checkbox" class="unique-input" name="unique[]"><button type="button" class="row-dynamic" style="background-color: #E3F6CE">Add subrows</button><div id=\"'+subrow_name+'\" value=' + val_2 + '></div></fieldset>';
$('#rows').append(rowHTML);
});
$("input.name-input").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
$("input.table-name").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
});
</script>
<!-- Script to add subrows -->
<script>
jQuery(function($) {
$('.row-dynamic').click(function () {
$('#subrowitems').val(function(i, val) { return +val+1 });
var val_3=$('#subrowitems').attr('value');
var subrowHTML = '<fieldset class="subrow-fieldset" value=\"' +val_3+ '\"><label id="subrow-label">Subrow:</label><input type="text" class="subrow-name-input" name="name[]" placeholder="Name" size="20" style="background-color: #E3F6CE"><input type="text" class="subrow-type-input" name="type[]" placeholder="Type [Ex: bigint(20)]" size="20" style="background-color: #E3F6CE"><span id="subrow-null-label">Null</span><input type="checkbox" class="subrow-null-input" name="null[]" style="background-color: #E3F6CE"><input type="text" class="subrow-default-input" name="default[]" placeholder="Default Value" size="20" style="background-color: #E3F6CE"><span id="subrow-unique-label">Unique</span><input type="checkbox" class="subrow-unique-input" name="unique[]" style="background-color: #E3F6CE"></fieldset>';
var subrow_val = '#subrows'+$('#row-fieldset').attr('value');
$(subrow_val).append(subrowHTML);
});
$("input.subrow-name-input").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
$("input.table-name").on({
keydown: function(e) {
if (e.which === 32)
return false;
},
change: function() {
this.value = this.value.replace(/\s/g, "");
}
});
});
</script>

You had some duplicated id's on your HTML sintax (e.g. #row-fieldset)
If you check your HTML code you initializes a fieldset tag with the row-fieldset id
<fieldset class="row-fieldset" id="row-fieldset" value="1">
and later you create a new one with the same id
var rowHTML = '<fieldset class="row-fieldset" id="row-fieldset" value=\"'+val_2+'\
So when JQuery tries to find the proper id, only find the first one.
I added to the Add subrows button a value for locate the correct row
Also you did not provide any jQuery version so I used 2.2.0
Check this fiddle to see it running
Hope it helps

Related

how to do html form vaildation in jquery

i am using html and jquery to do some form vaildations
for ex if user click on a field and doesn't enter any thing, than he clicks on different field... i want to turn field border to red. this way user will know that he can not skip this field...
also when user clicks on button submit, than i also want to do this same, if field is empty than turn border to red
below is what i have so far, is there a better way to do this? bbc it seem like i am repeating alot of same code
on up side it does work fine, so guess i can just keep on repeating code
note i have like 20+ fields so jquery function will be long
forgot to tell that i am using asp fields:
<asp:TextBox ID="FirstNameCTB" ClientIDMode="Static" class="input form-control input-md" runat="server"></asp:TextBox>
javascript code:
<script type="text/javascript">
$(function () {
$('#FirstNameCTB').blur('input', function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '')
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
});
$('#LastNameCTB').blur('input', function () {
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '')
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
});
$('.CHECKOUTLBC').click(function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '') {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
}
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '') {
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
}
});
});
</script>
https://jqueryvalidation.org/ can be your solution.
Also here's the examples.
https://jqueryvalidation.org/files/demo/
This plugin has, red border, submit control etc.
Also this plugin will be good.
http://www.formvalidator.net/#reg-form
$.validate({
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
// Restrict presentation length
$('#presentation').restrictLength( $('#pres-max-length') );
<form action="" id="registration-form">
<p>
E-mail
<input name="email" data-validation="email">
</p>
<p>
User name
<input name="user" data-validation="length alphanumeric"
data-validation-length="3-12"
data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
</p>
<p>
Password
<input name="pass_confirmation" data-validation="strength"
data-validation-strength="2">
</p>
<p>
Repeat password
<input name="pass" data-validation="confirmation">
</p>
<p>
Birth date
<input name="birth" data-validation="birthdate"
data-validation-help="yyyy-mm-dd">
</p>
<p>
Country
<input name="country" id="country" data-validation="country">
</p>
<p>
Profile image
<input name="image" type="file" data-validation="mime size required"
data-validation-allowing="jpg, png"
data-validation-max-size="300kb"
data-validation-error-msg-required="No image selected">
</p>
<p>
User Presentation (<span id="pres-max-length">100</span> characters left)
<textarea name="presentation" id="presentation"></textarea>
</p>
<p>
<input type="checkbox" data-validation="required"
data-validation-error-msg="You have to agree to our terms">
I agree to the terms of service
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
Assuming all your form inputs are called input, you could loop through them and apply the function with something similar to this.
var inputs = document.getElementsByTagName('input');
for(n = 0; n < inputs.length; n++){
$(function () {
inputs[n].blur('input', function () {
if (inputs[n].val().trim() == '')
inputs[n].css('border-color', 'red');
else
inputs[n].css('border-color', '');
});
});
}
couple things:
issue maybe be that javascript is beeing run before the controls
you should not mix core javascript with jquery libary
you do not need loop when using blur, on, click, etc jquery functions
keeping all those above things in mind, below is a better solutions. works for me
$(function () {
$(".input").blur(function () {
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
});
Have a look at this example below.
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>
Have a look at this example:

The order of my jquery validator is working wrong, and I have no idea why

My form validator works, but it works in a certain order, if I check the checkbox, it works fine, but if I fill the inputs first and then use the checkbox, it not works, unless I type something in the inputs
$(document).ready(function() {
$('#send').attr('disabled', true);
$('.input,#check').on('keyup', function() {
var text_value = $('.input-cpk').val();
if (text_value !== '' && (document.getElementById('check').checked)) {
$('#send').attr('disabled', false);
} else {
$('#send').attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="block oh fr col-9 margem-d2 text-left" action="enviar-calculo.php" method="post" target="votar" name="cpk">
<input type="text" name="nome" id="nome" class="input-cpk col-20">
<input type="number" name="telefone" class="input-cpk-tel">
<input type="submit" value="CALCULAR" id="send" class="f-josefin-s-b f-branca bg-amarelo botao" onclick="output();">
<input type="checkbox" id="check" name="others" />
</form>
You only run your validation code during the keyup event, which only happens on the input boxes. You also need to do validation during a click event on the checkbox.
You can put multiple event names in the argument to .on(), to handle both with the same code.
You also have an incorrect class .input, there are no elements with class="input" in the HTML. I've changed it to .input-cpk.
$(document).ready(function() {
$('#send').prop('disabled', true);
$('.input-cpk,#check').on('keyup click', function() {
var text_value = $('.input-cpk').val();
if (text_value !== '' && (document.getElementById('check').checked)) {
$('#send').prop('disabled', false);
} else {
$('#send').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="block oh fr col-9 margem-d2 text-left" action="enviar-calculo.php" method="post" target="votar" name="cpk">
<input type="text" name="nome" id="nome" class="input-cpk col-20">
<input type="number" name="telefone" class="input-cpk-tel">
<input type="submit" value="CALCULAR" id="send" class="f-josefin-s-b f-branca bg-amarelo botao" onclick="output();">
<input type="checkbox" id="check" name="others" />
</form>
It's because you're using the wrong selector.
Try this
$('input,#check').on('keyup', function() {
Instead of this
$('.input,#check').on('keyup', function() {
Additionally you might want to use the .on('change') instead of .on('keyup')

How to transfer values from between input

Before anyone marks this as a duplicate, I have looked at many sites and am currently using this one - jQuery - passing value from one input to another for guidance, yet no result... I am trying to pass a value from one input in one form to another input in a 'table'. I have put it in a table because of a very weird reason - it does not display a Sparql value when in a form only displays in a table so the input was placed in a table. My code is below:
Form
<form onclick="txtFullName.value = txtFirstName.value +'_'+ txtLastName.value">
First name : <input type="text" name="txtFirstName" value="#ViewBag.FirstName"/> <br><br>
Last name : <input type="text" name="txtLastName" value="#ViewBag.LastName" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
Table
<table id="results">
<Full name:
<br>
<input id="userInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="submit" type="submit" value="Submit">
</table>
JQUERY
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('txtFullName').val($(this).val());
});
});
I am trying to display the txtFullName into userInput input when pressing submit but right now only the `txtFullName' is displayed when pressing submit. Also the submit is the submit button in the FORM.
Anymore info needed let me know:)
You need to change the onclick to action on the form if you are trying to use submit button. The other way is to use input type button instead of submit:
So:
$(document).ready(function() {
$('#submit12').on('click', function (e) {
console.log('test');
$("#txtFullName").val($("#txtFirstName").val() + '_' + $("#txtLastName").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
First name : <input type="text" id="txtFirstName" value="First"/> <br><br>
Last name : <input type="text" id="txtLastName" value="Last" /> <br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="submit12" type="button" value="Submit">
</form>
If you want to display txtFullName into userInput, simply do something like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').val($('#txtFullName').val());
});
And why do you need change function there , if yo need changes when click submit.
Edit your JQuery like this:
$('#submit12').on('click', function (e) { //Form submit
$('#userInput').change(function () {
$('#txtFullName').val($(this).val());
});
});
$('#submit').on('click', function () { //Form submit
$('#userInput').val($('#txtFullName').val());
});
I don't clearly understand why you do it but It can fix your code.
It is not entirely clear what the two buttons do, but the operation itself is really very simple. See comments inline for explanations:
// Wait until the DOM is loaded and all elements are avaialble
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you'll need
var theForm = document.getElementById("frmTest");
var txtFirstName = document.getElementById("txtFirstName");
var txtLasttName = document.getElementById("txtLastName");
var txtFulltName = document.getElementById("txtFullName");
var txtUserInput = document.getElementById("txtUserInput");
var btn1 = document.getElementById("btnSubmit1");
var btn2 = document.getElementById("btnSubmit2");
// Function to join names together
function combine(){
txtFullName.value = txtFirstName.value + '_' + txtLastName.value;
}
// Set event handlers
frmTest.addEventListener("click", combine);
btn1.addEventListener("click", combine);
});
<!-- Keep you JavaScript out of your HTML -->
<form id="frmTest">
First name : <input type="text" id="txtFirstName" name="txtFirstName" value="#ViewBag.FirstName">
<br><br>
Last name : <input type="text" id="txtLastName" name="txtLastName" value="#ViewBag.LastName" >
<br><br>
Full name : <input type="text" id="txtFullName" name="txtFullName"> <br><br />
<input id="btnSubmit1" type="button" value="Combine Names">
<table id="results">
<Full name:
<br>
<input id="txtUserInput" type="text" name="fullname" ${userJson.userId == ''?'': 'disabled'} value="#ViewBag.DisplayName">
<br>
<input id="btnSubmit2" type="submit" value="Submit">
</table>
</form>

parent form and child forms to display a value on checked javascript

I have a webpage with multiple forms, each form has a distinct form id. I need the java script to display a string in the field when a box is checked. This works for the first form, does not work for the rest on the page.
Webpage code:
<div class="form" id="form-products_483"><form id="products_483" name="products_483" enctype="application/x-www-form-urlencoded" method="post" jshandler="" action="">
<div class="form-element hidden" id="form-element-id__483">
<input type="hidden" name="id__483" value="483" class="p_id" id="id__483"></div>
<div class="product-form-element text" id="form-element-v_one_fees_cost_f"> <label for="v_one_fees_cost_f" class="form-element-label optional">$ of one-time fixed fee</label>
<input type="text" name="v_one_fees_cost_f" id="v_one_fees_cost_f" value="" maxlength="9" class="v_one_fees_cost_f" placeholder="xx.xx"></div>
<div class="product-form-element checkbox" id="form-element-v_varies"><label for="v_varies" class="form-element-label optional">Varies</label>
<input type="hidden" name="v_varies" value="0"><input type="checkbox" name="v_varies" id="v_varies" value="1" checked="checked"></div>
Ongoing fees
My javascript code:
$(document).on('change', '#v_one_fees_f', function(e) {
block_($(this).parents('form').find('.v_one_fees_cost_f'), $(this).val());
if($(this).val() != 'Yes') {
$(this).parents('form').find('#v_varies').attr('disabled', 'disabled');
}
else {
$(this).parents('form').find('#v_varies').removeAttr('disabled');
}
});
$(document).on('change', '#v_varies', function(e) {
inputVaries($("#v_one_fees_cost_f"), $(this));
});
function inputVaries(form_input, checkbox){
if (checkbox.is(':checked')) {
form_input.val("Varies");
}
else{
form_input.val("");
}
}
Note: I am completely new to java script. Even if you could direct me to some tutorial. It would be of great help.

jQuery, submit() with multiple forms using .each()

First off, I realize this is not an optimal solution, but the actual production environment is a product of a drunken orgy involving Magento and a lot of cheap plugins, so don't judge me too harshly. I can't be held responsible for other peoples' messes.
I'm trying to submit multiple forms from one page using jQuery. It works fine in IE and FF. Page has four forms, which I loop through them in JS to see if their checkbox is checked and then submit them one by one, using .each() and .submit(). In Chrome, jQuery(this).submit() does not fire until after you have completely exited the function, and then it only actually submits the last form.
Uses jQuery 1.8.1. The working mockup is here
The code follows:
<!DOCTYPE html>
<html>
<head>
<title>asdfad</title>
<script type="text/javascript" src=http://code.jquery.com/jquery-1.8.1.min.js"></script>
</head>
<body class=" listraknewsletter-index-index">
<form id="form4" method="post" class="signup-form"
action="http://www.example.com/action1"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue1"/>
<label for="checkbox">newsletter 1</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form2" method="post" class="signup-form"
action="http://www.example.com/action2"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue2"/>
<label for="checkbox">newsletter 2</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form3" method="post" class="signup-form"
action="http://www.example.com/action3"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue3"/>
<label for="checkbox">newsletter 3</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<form id="form1" method="post" class="signup-form"
action="http://www.example.com/action4"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue4"/>
<label for="checkbox">newsletter 4</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<!-- Area for entering in information -->
<form method="post" action="/">
<label for="email">email</label>
<input type="text" id = "nl_email" name="email"
size="40" maxlength="100" value = ""/>
<label for="name">name</label>
<input type="text" name="name" id = "nl_name" maxlength="50" size="40" value=""/>
<input type="button" value="Subscribe" onclick="processSignups();" />
<script type="text/javascript">
// requires jQuery
jQuery.noConflict();
function processSignups() {
// make sure you have a valid email and name
// make sure email is at least not null
// this is not a pretty regex for sure lol,
// but tis' RFC 2822 valid
var nl_email = jQuery('input#nl_email').val();
var re = new RegExp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
if (re.test(nl_email) == false) {
alert('Please enter a valid email');
return false;
}
// name is not null
if (jQuery('input#nl_name').val() == '') {
alert('Please enter your name');
return false;
}
// make sure at least one checkbox is selected
var checkboxes = jQuery('input.signup-checkbox');
var atLeastOne = false;
jQuery(checkboxes).each(function() {
if (jQuery(this).is(':checked')) {
atLeastOne = true;
}
});
if (atLeastOne == false) {
alert('Please select at least one newsletter checkbox');
return false;
}
// select your forms by class
// var forms = jQuery('form.signup-form');
// for each form
var formIds = new Array();
jQuery('form.signup-form').each(function(index) {
// get the checkbox
var checkbox;
checkbox = jQuery(this).children('input.signup-checkbox');
// if it is checked
if (jQuery(checkbox).is(':checked')) {
// add a hidden field to the form to hold the email
jQuery(this).append('<input type="hidden" name="email" value="' + nl_email + '" />');
// and submit form
jQuery(this).submit();
}
});
// might as well clear the email and name inputs
jQuery('input#nl_name').val('');
jQuery('input#nl_email').val('');
// return false;
}
</script>
</form>
</body>
</html>
Chrome doesn't treat target="_blank" like the other browsers. Try _tab, or dynamically changing them $(this).attr('target', '_'+$(this).attr('id'));

Categories

Resources