I'm appending a form after successful AJAX call. When i'm trying to put validations by using id of that form its not working. Below is the example of my code.
HTML
<div id="dynamic_form"></div>
JavaScript
tab += '<form id="edu_edit_datails" method="post" action="" name="edu_edit_datails" enctype="multipart/form-data">';
tab += '<div class="form-group">';
tab += '<label for="course">Course:</label>';
tab += '<input type="text" class="form-control" id="course" value="" placeholder="Enter your Course" name="course">';
tab += '</div>';
tab += '<button type="button" class="btn btn-primary " id="submit_edit_edu_dtls">Submit</button>';
tab += '</form>';
$('#dynamic_form').html(tab);
Validation on click
$(document).on('click', '#submit_edit_edu_dtls' , function(e){
if($("#edu_edit_datails").valid() == false) {
alert("fail");
return false;
} else {
alert(success);
return true;
}
});
$("#edu_edit_datails").validate({
rules: {
course: "required"
}
})
Any help is greatly appreciated! Thanks in advance.
You just need to validate the form (.validate) before you use the .valid()
var tab="";
tab += '<form id="edu_edit_datails" method="post" action="" name="edu_edit_datails" enctype="multipart/form-data">';
tab += '<div class="form-group">';
tab += '<label for="course">Course:</label>';
tab += '<input type="text" class="form-control" id="course" value="" placeholder="Enter your Course" name="course">';
tab += '</div>';
tab += '<button type="button" class="btn btn-primary " id="submit_edit_edu_dtls">Submit</button>';
tab += '</form>';
$('#dynamic_form').html(tab);
$("#edu_edit_datails").validate({
rules: {
course: "required"
}
})
$(document).on('click', '#submit_edit_edu_dtls' , function(e){
if($("#edu_edit_datails").valid() == false){
alert("fail");
return false;
}else{
alert("success");
return true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>
<diV id="dynamic_form"></div>
Related
I have an issue in showing filenanme to its corresponding field.
Now,
When i browse a file in the appended div,then it's file name is shown in the parent div instead of dynamically appended div.
Form
<!-- start other_docx -->
<div class="img_field">
<div class="j-row ">
<label class="j-label">Other Documents</label>
<div class="j-span9 j-unit">
<label class="j-input j-append-small-btn">
<label class="j-icon-left" for="files[]">
<i class="fa fa-download"></i>
</label>
<div class="j-file-button">
Browse
<!-- <input type="file" name="files[]" onchange="document.getElementById('files[]').value=this.value;"> -->
<input type="file" name="files[]" onchange="setfilename(this.value);">
</div>
<input type="text" id="files[]" readonly="" placeholder="No file selected">
<span class="j-hint">Only: jpg / png / Pdf</span>
</label>
</div>
<div class="j-span3 j-unit">
<div class="" style="margin-top:5px">
<button style="" class="btn btn-sm btn-primary add_more_button">Add more</button>
</div>
</div>
</div>
</div>
<!-- end other_docx -->
setfilename()
<script>
function setfilename(val)
{
var fileName = val.substr(val.lastIndexOf("\\")+1, val.length);
document.getElementById("files[]").value = fileName;
}
</script>
js
$(document).ready(function() {
var max_fields_limit = 10; //set limit for maximum input fields
var x = 1; //initialize counter for text box
$('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
e.preventDefault();
if(x < max_fields_limit){ //check conditions
x++; //counter increment
// $('.img_field').append('<div><input type="file" name="files[]" class="form-control"/>Remove</div>'); //add input field
// var name="document.getElementById('files[]').value=this.value;";
$('.img_field').append('<div class="j-row">' +
'<div class="j-span9 j-unit">' +
'<label class="j-input j-append-small-btn">' +
'<label class="j-icon-left" for="files[]">' +
'<i class="fa fa-download"></i>' +
'</label>' +
'<div class="j-file-button"> Browse' +
'<input type="file" name="files[]" onchange="setfilename(this.value);">' +
// '<input type="file" name="files[]" onchange="'+name+'">' +
'</div>' +
'<input type="text" id="files[]" readonly="" placeholder="No file selected">' +
'<span class="j-hint">Only: jpg / png</span>' +
'</label>' +
'</div>' +
'<div class="j-span3 j-unit">' +
'<div class="" style="margin-top:5px">' +
'<button style="" class="btn btn-sm btn-danger remove_field">Remove</button>' +
'</div>' +
'</div>' +
'</div>');
}
});
$('.img_field').on("click",".remove_field", function(e){ //user click on remove text links
e.preventDefault();
// $(this).parent('div').remove();
$(this).closest("div.j-row").remove();
x--;
})
});
and this is what my form looks like..
enter image description here
I'm kinda new to jquery.. any help will be greatly appreciated.
Thank you in advance.!
//Edit
working fine now.I just replaced the id 'files[]' with a unique id for each dynamically created element.
Thanks to Ouroborus for mentioning the mistake.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
This is my HTML form:
<form class="access_form" action="/elements/login.php" method="POST">
<div class="logo">
<img src="/img/brand/logo.png" alt="logo" class="brand">
</div>
<div class="form">
<div class="input_container">
<input type="text" placeholder="Username" name="username" required>
<input type="password" placeholder="Password" name="password" required>
<button type="submit" name="login" id="submit">Login</button>
<p id="alert"></p>
<h5 class="linked_text_forgot"><a class="linked_text_forgot" href="javascript:">Forgot your password?</a></h5>
</div>
<div class="small_container">
<h5 class="linked_text_signup">Click here to <a class="linked_text_signup" href="" onclick="return switch_form('sign_up');">Sign up</a></h5>
</div>
</div>
</form>
This is my javascript:
// form switching function to login or signup form
function switch_form(type) {
if (type == "login") {
$( 'form.access_form' ).replaceWith(login);
} else if (type == "sign_up") {
$( 'form.access_form' ).replaceWith(sign_up);
}
return false;
}
$( document ).ready(function() {
$(".access_form").submit(function(event){
event.preventDefault();
});
});
// sign up form
var sign_up = '<form class="access_form" action="/elements/signup.php" method="POST">' +
'<div class="logo">' +
'<img src="/img/brand/logo.png" alt="logo" class="brand">' +
'</div>' +
'<div class="form">' +
'<div class="input_container">' +
'<input type="text" placeholder="Full name" name="fullname">' +
'<input type="text" placeholder="Email" name="email" id="user_email">' +
'<input type="text" placeholder="Username" name="username" id="user_uid">' +
'<input type="password" placeholder="Password" name="password" id="user_pswd">' +
'<button type="submit" name="sign_up" id="submit">Sign Up</button>' +
'<p class="alert"></p>' +
'</div>' +
'<div class="small_container">' +
'<h5 class="linked_text_signup">Click here to <a class="linked_text_signup" href="" onclick="return switch_form("login");">Login</a></h5>' +
'</div>' +
'</div>' +
'</form>';
// login form
var login = '<form class="access_form" action="/elements/login.php" method="POST" id="login">' +
'<div class="logo">' +
'<img src="/img/brand/logo.png" alt="logo" class="brand">' +
'</div>' +
'<div class="form">' +
'<div class="input_container">' +
'<input type="text" placeholder="Username" name="username" required>' +
'<input type="password" placeholder="Password" name="password" required>' +
'<button type="submit" name="login">Login</button>' +
'<p class="alert"></p>' +
'<h5 class="linked_text_forgot"><a class="linked_text_forgot" href="javascript:">Forgot your password?</a></h5>' +
'</div>' +
'<div class="small_container">' +
'<h5 class="linked_text_signup">Click here to <a class="linked_text_signup" href="" onclick="return switch_form("sign_up");">Sign up</a></h5>' +
'</div>' +
'</div>' +
'</form>';
So from my previous question i've found out that preventdefault works on the normally loaded html elements when the page starts however if you look at the javascript im loading in a signup form without reloading the page using jquery. I think that's why the preventdefault is not working on the html elements that are loaded on the page.
any suggestions for how i could go about this?
Basically Jquery attaches event handlers to elements only once, when the page is first loaded. Any elements that are created dynamically (don't exist when the page first loads), will need to have the event handlers manually added to them or you can attach the event handler to an element higher in the DOM that existed from page load. In your example you can attach the event handler to the document, which exists the entire time, and tell it to look for submit events from .access_form elements.
The answer on this page explains it a little better.
Click event doesn't work on dynamically generated elements
$( document ).on('submit','.access_form', function(event){
event.preventDefault();
});
I'm planning to use a form to register new Teacher (see image bellow). A teacher can assign to different classes to teach different subjects.
Is it possible to pass the value from textbox in Row1_Column1 (AAAA) to textbox in Row2_Column1 when a new row is created by clicking on button (+)?
I don't want the user to take pain in typing the same values in some of the textboxes - the values will be the same. Only [Subject Taught] and [Class Taught] columns might be different, so i want to leave those empty for every new row created.
Sample Form
My code is as follows:
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<div class="row">
<div class="col-xs-12">
<p><button class="btn btn-success" type="button" name="viewStaff">
<i class="ace-icon fa fa-eye bigger-120"></i>
View List</button>
</p>
<form method="post" id="insert_form">
<span id="error"></span>
<table class="table table-bordered" id="staff_table">
<thead>
<tr>
<th>Name (Initials)</th>
<th>Username</th>
<th>Password</th>
<th>Role</th>
<th>Class Assigned</th>
<th>Subject Taught</th>
<th>Class Taught</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</thead>
</table>
<div class="space-24"></div>
<div class="clearfix form-actions">
<div class="center">
<button class="btn btn-info" type="submit" name="submit">
<i class="ace-icon fa fa-check bigger-110"></i>
Submit
</button>
<button class="btn" type="reset">
<i class="ace-icon fa fa-undo bigger-110"></i>
Reset
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="initials[]" class="form-control initials" /></td>';
html += '<td><input type="text" name="user_name[]" class="form-control user_name" /></td>';
html += '<td><input type="password" name="password[]" class="form-control password" /></td>';
html += '<td><select name="role[]" class="form-control role"><option value="">Select...</option><option value="admin">Admin</option><option value="form_master">Form Master</option><option value="staff">Staff</option></select></td>';
html += '<td><select name="class_assigned[]" class="form-control class_assigned"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
html += '<td><select name="subject_taught[]" class="form-control subject_taught"><option value="">Select...</option><?php echo fill_subject_box($conn); ?></select></td>';
html += '<td><select name="class_taught[]" class="form-control class_taught"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#staff_table').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.initials').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.user_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.password').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.role').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_assigned').each(function(){
var count = 1;
if($(this).val() == '')
{
return true;
}
count = count + 1;
});
$('.subject_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"staff_insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#staff_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Staff Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
And staff_insert.php
<?php
//staff_insert.php
$connect = mysqli_connect("localhost", "root", "", "studentsdatabase");
if(isset($_POST["initials"]))
{
$initials = $_POST["initials"];
$user_name = $_POST["user_name"];
$password = $_POST["password"];
$role = $_POST["role"];
$class_assigned = $_POST["class_assigned"];
$subject_taught = $_POST["subject_taught"];
$class_taught = $_POST["class_taught"];
$query = '';
for($count = 0; $count<count($initials); $count++)
{
$initials_clean = mysqli_real_escape_string($connect, $initials[$count]);
$user_name_clean = mysqli_real_escape_string($connect, $user_name[$count]);
$password_clean = mysqli_real_escape_string($connect, $password[$count]);
$role_clean = mysqli_real_escape_string($connect, $role[$count]);
$class_assigned_clean = mysqli_real_escape_string($connect, $class_assigned[$count]);
$subject_taught_clean = mysqli_real_escape_string($connect, $subject_taught[$count]);
$class_taught_clean = mysqli_real_escape_string($connect, $class_taught[$count]);
if($initials_clean != '' && $user_name_clean != '' && $password_clean != '' && $role_clean != '' && $class_assigned_clean != '' && $subject_taught_clean != '' && $class_taught_clean != '')
{
$query .= '
INSERT INTO tbl_users(fullname, username, password, role, class_assigned, subject_taught, class_taught)
VALUES("'.$initials_clean.'", "'.$user_name_clean.'", "'.$password_clean.'", "'.$role_clean.'", "'.$class_assigned_clean.'", "'.$subject_taught_clean.'", "'.$class_taught_clean.'");
';
}
}
if($query != '')
{
if(mysqli_multi_query($connect, $query))
{
echo 'ok';
}
}
}
?>
Please if you know of a better way, kindly help.
Thanks.
EDIT:
New Image Please check this image
How can I manipulate the above jquery to make the Name, Username, Password, Role and Class Assigned appear for each row the remaining inputs Subject Taught and Class Taught?
Please help.
Some fields are not populated as no server side data can be retrived here. Bu you can see the example for the Role column.
Look for this part in the snippet:
// Here is were you can do the conditional and copying part
var last_row_role_sel_val = $('#staff_table tr:last td:nth-child(4) select option:selected').val();
var last_row_role_sel_html = $('#staff_table tr:last td:nth-child(4) select option:selected').html();
console.log('last_row_role_sel_val',last_row_role_sel_val);
console.log('last_row_role_sel_html',last_row_role_sel_html);
And the replacement part
if (last_row_role_sel_val!=undefined && last_row_role_sel_val!="") {
html += '<td><select name="role[]" class="form-control role"><option value="'+last_row_role_sel_val+'">'+last_row_role_sel_html+'</option></select></td>';
} else {
...
//$( "b" ).clone().prependTo( "p" );
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
// Here is were you can do the conditional and copying part
var last_5_rows_sel_val = [];
var last_5_rows_sel_html = [];
for (var i=1;i<=5;i++) {
if (i>=4) {
last_5_rows_sel_val.push($('#staff_table tr:last td:nth-child('+i+') select option:selected').val());
last_5_rows_sel_html.push($('#staff_table tr:last td:nth-child('+i+') select option:selected').html());
} else {
last_5_rows_sel_val.push($('#staff_table tr:last td:nth-child('+i+') input').val());
last_5_rows_sel_html.push('');
}
}
if (last_5_rows_sel_val[0]!=undefined && last_5_rows_sel_val[0]!="") {
html += '<td><input type="text" name="initials[]" class="form-control initials" value="'+last_5_rows_sel_val[0]+'" /></td>';
html += '<td><input type="text" name="user_name[]" class="form-control user_name" value="'+last_5_rows_sel_val[1]+'" /></td>';
html += '<td><input type="password" name="password[]" class="form-control password" value="'+last_5_rows_sel_val[2]+'" /></td>';
html += '<td><select name="role[]" class="form-control role"><option value="'+last_5_rows_sel_val[3]+'">'+last_5_rows_sel_html[3]+'</option></select></td>';
html += '<td><select name="class_assigned[]" class="form-control class_assigned"><option value="'+last_5_rows_sel_val[4]+'">'+last_5_rows_sel_html[4]+'</option></select></td>';
} else {
html += '<td><input type="text" name="initials[]" class="form-control initials" /></td>';
html += '<td><input type="text" name="user_name[]" class="form-control user_name" /></td>';
html += '<td><input type="password" name="password[]" class="form-control password" /></td>';
html += '<td><select name="role[]" class="form-control role"><option value="">Select...</option><option value="admin">Admin</option><option value="form_master">Form Master</option><option value="staff">Staff</option></select></td>';
html += '<td><select name="class_assigned[]" class="form-control class_assigned"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
}
html += '<td><select name="subject_taught[]" class="form-control subject_taught"><option value="">Select...</option><?php echo fill_subject_box($conn); ?></select></td>';
html += '<td><select name="class_taught[]" class="form-control class_taught"><option value="">Select...</option><?php echo fill_class_box($conn); ?></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">-</span></button></td></tr>';
$('#staff_table').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.initials').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.user_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.password').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.role').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_assigned').each(function(){
var count = 1;
if($(this).val() == '')
{
return true;
}
count = count + 1;
});
$('.subject_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
$('.class_taught').each(function(){
var count = 1;
if($(this).val() == '')
{
error = "<p>Please enter the required information</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"staff_insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#staff_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Staff Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
table,th,tr,td,div,p {
border: 1px solid #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-12">
<!-- PAGE CONTENT BEGINS -->
<div class="row">
<div class="col-xs-12">
<p><button class="btn btn-success" type="button" name="viewStaff">
<i class="ace-icon fa fa-eye bigger-120"></i>
View List</button>
</p>
<form method="post" id="insert_form">
<span id="error"></span>
<table class="table table-bordered" id="staff_table">
<thead>
<tr>
<th>Name (Initials)</th>
<th>Username</th>
<th>Password</th>
<th>Role</th>
<th>Class Assigned</th>
<th>Subject Taught</th>
<th>Class Taught</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus">+</span></button></th>
</tr>
</thead>
</table>
<div class="space-24"></div>
<div class="clearfix form-actions">
<div class="center">
<button class="btn btn-info" type="submit" name="submit">
<i class="ace-icon fa fa-check bigger-110"></i>
Submit
</button>
<button class="btn" type="reset">
<i class="ace-icon fa fa-undo bigger-110"></i>
Reset
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
UPDATED!!
I am very new in jsp, and jquery
my code create dynamic text boxes and one drop-down menu based on button clicked,
after created textboxes I want to add one more textbox if the user select option male after the text boxes dynamically added.
the add code works, but the text box when selecting the male option not works.
please please help.
this is my code
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<br />
<div class="container">
<h3 align="center">Change Control Board (CCB)</h3>
<br />
<h4 align="center">Enter Change Details</h4>
<br />
<form name="form1" method="GET" action="jsv" id="form1">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Enter Change Name</th>
<th>Enter Change Description</th>
<th>Enter Change GW</th>
<th>Enter Change AW</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr> name="change_name1[]"';
html += '<td><input type="text" name="change_name[]" class="form-control change_name" /></td>';
html += '<td><textarea name="change_desc[]" class="form-control change_desc rows="3"" /></td>';
html += '<td><input type="text" name="change_GW[]" class="form-control change_GW" /></td>';
html += '<td><input style="display:none;" id="business" type="text" name="change_G[]" class="form-control change_GW" /></td>';
html += '<td><select id="purpose" name="sex-type" class="form-control item_unit"><option value="0">select</option><option value="1">male</option><option value="2">Passing on to a client</option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
});
});
$(document).ready(function() {
$('#purpose').on('change', function() {
if (this.value == '1') {
$("#business").show();
} else {
$("#business").hide();
}
});
});
</script>
First of all you have an error on the first line where you are concatenating the tr in the $html, it is '<tr> name="change_name1[]"'; where as it should be '<tr name="change_name1[]">'; but since the name attribute is not a valid attribute for tr you should change it to a unique id.
I hope the select menu and the input boxes that are generated by the click of a button are not multiple as there is an id attribute on the select input which needs to be unique in case there are multiple select boxes, but since it is not mentioned you make a slight change to your event binding like the code below
You must change the id attributes from static to dynamic something like appending a count along with their ids i have added it for you hope it solves your problem.
your final script will look like this
$(document).ready(function () {
var count = 0;
$(document).on('click', '.add', function () {
var html = '';
html += '<tr>';
html +='<td><input type="text" name="change_name[]" class="form-control change_name" /></td>';
html +='<td><textarea name="change_desc[]" class="form-control change_desc rows="3"" /></td>';
html +='<td><input type="text" name="change_GW[]" class="form-control change_GW" /></td>';
html += '<td><input style="display:none;" id="business_' + count +
'" type="text" name="change_G[]" class="form-control change_GW" /></td>';
html += '<td><select id="purpose_' + count +
'" name="sex-type" class="form-control item_unit"><option value="0">select</option><option value="1">male</option><option value="2">Passing on to a client</option></select></td>';
html +=
'<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
$('#purpose_' + count).on('change', function () {
if (this.value == '1') {
$("#business_"+count).show();
} else {
$("#business_"+count).hide();
}
});
count++;
});
$(document).on('click', '.remove', function () {
$(this).closest('tr').remove();
});
});
Cut this code:
$('#purpose').on('change', function() {
if ( this.value == '1')
{
$("#business").show();
}
else
{
$("#business").hide();
}
}
and paste it right behind $('#item_table').append(html);
Two $(document).ready() sections make no sense. And the event handler (on click) needs to be attached after you create the select box.
You are adding select dynamically at run time.so, after adding Select You need to bind it's change event.
So Just make change into your javascript code
<script>
$(document).ready(function(){
counter=0;
$(document).on('click', '.add', function(){
counter=counter+1;
var html = '';
html += '<tr> name="change_name1[]"';
html += '<td><input type="text" name="change_name[]" class="form-control change_name" /></td>';
html += '<td><textarea name="change_desc[]" class="form-control change_desc rows="3"" /></td>';
html += '<td><input type="text" name="change_GW[]" class="form-control change_GW" /></td>';
html += '<td><input style="display:none;" id="business_'+counter+'" type="text" name="change_G[]" class="form-control change_GW" /></td>';
html += '<td><select id="purpose_'+counter+'" name="sex-type" class="form-control item_unit"><option value="0">select</option><option value="1">male</option><option value="2">Passing on to a client</option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
$('#purpose_'+counter).on('change', function() {
if ( this.value == '1')
{
$("#business_"+counter).show();
}
else
{
$("#business_"+counter).hide();
}
});
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
});
</script>
I want to add a form including an input text using javascript.
the adding works fine, but if i click the submit button nothing happens.
Here is the code:
if (document.getElementById("run_name_query_box") == null) {
var run_name_search = '<fieldset id="run_name_query_box">' +
'<table> <td><tr>' +
'<p style="font-size:16px"> Runname:</p>' +
'<input type="text" style="font-size:16px" id="run_name">' +
'<form method="post" action=query name="query_runname_name">' +
'<input style="font-size:14px" value="Search Database" onclick= "run_name_querycreator()" id="search_run_name_id" type="submit" name="search_run_name_name"> ' +
'</form>' +
'</tr></td></table>' +
'</fieldset>';
$("#query_type_box").append(run_name_search);
}
the run_name_querycreator() function sets the value of the input.
I already use almost the same thing somewhere else and there it works:
'<form method="post" action=query name="query">' +
'<input style="font-size:14px" value = "Search Database" onclick = "combine_query()" id="search" type="submit" name="search" >' +
'</form>'
If i copy the plain html part just into the main html body it works too.
This is all part of mako file used in a pyramid interface.
I think your HTML is malformed. I don't think a form element can be a child of a table element.
Your code should be like this,
var run_name_search = '<fieldset id="run_name_query_box">' +
'<form method="post" action=query name="query_runname_name">' +
'<table>'+
'<tr><td>' +
'<p style="font-size:16px"> Runname:</p>' +
'<input type="text" style="font-size:16px" id="run_name">' +
'<input style="font-size:14px" value="Search Database" onclick= "run_name_querycreator()" id="search_run_name_id" type="submit" name="search_run_name_name"> ';
$("#query_type_box").append(run_name_search);
This is your code generated HTML,
<fieldset id="run_name_query_box">
<p style="font-size:16px">Runname:</p>
<input style="font-size:16px" id="run_name" type="text">
<input style="font-size:14px" value="Search Database" onclick="run_name_querycreator()" id="search_run_name_id" name="search_run_name_name" type="submit">
<table>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<form method="post" action="query" name="query_runname_name"></form>
</tr>
</tbody>
</table>
</fieldset>
There is no form elements in within your <form>. (Including your form submit button). Then How it will work?
Your code should generate HTML like this to work,
<fieldset id="run_name_query_box">
<form method="post" action="query" name="query_runname_name">
<table>
<tbody>
<tr>
<td>
<p style="font-size:16px">Runname:</p>
<input style="font-size:16px" id="run_name" type="text">
<input style="font-size:14px" value="Search Database" onclick="run_name_querycreator()" id="search_run_name_id" name="search_run_name_name" type="submit">
</td>
</tr>
</tbody>
</table>
</form>
</fieldset>
See this FIDDLE
In this fiddle You can see BEFORE FIX section dynamic elements generated by you.
In AFTER FIX section you can see the correct html format.
FYI, When you are working with Dynamic html, Check you dynamically created html in developers tool.
Working example: http://jsfiddle.net/awesome/6hh8r/
Description: Added missing onclick function run_name_querycreator() in global namespace and connected it to .post() with apparent form data.
window.run_name_querycreator = function () {
//alert($('#run_name').val());
var x = '{"run_name":"' + $('#run_name') + '"}'
$.ajax({
type: "POST",
url: $form.attr('action'),
data: x,
success: alert('success'),
dataType: 'json'
});
}
$(function () {
if (document.getElementById("run_name_query_box") === null) {
var run_name_search = '<fieldset id="run_name_query_box">' +
'<table> <td><tr>' +
'<p style="font-size:16px"> Runname:</p>' +
'<input type="text" style="font-size:16px" id="run_name">' +
'<form method="post" action=query name="query_runname_name">' +
'<input style="font-size:14px" value="Search Database" onclick="run_name_querycreator()" id="search_run_name_id" type="submit" name="search_run_name_name"> ' +
'</form>' +
'</tr></td></table>' +
'</fieldset>';
$("#query_type_box").append(run_name_search);
$form = $('[name="query_runname_name"]');
$form.submit(function (e) {
e.preventDefault();
});
}
});