I have a form that I insert dynamically. When a link is clicked I execute this jQuery:
var newhtml = ' <div class="nav-wrapper"> <form id="target"> <div class="input-field"><input id="search" type="search" required> <label for="search"><i class="material-icons">search</i></label><i class="material-icons">close</i></div></form></div> ';
//replace nav bar with search bar
$("#replaceBar").replaceWith(newhtml);
I also have this in my javascript file:
$("#target").submit(function (event) {
alert("search submitted");
});
My issue is that I think the jquery for the submit is not being attached since the form is being submitted after the JS loads.
I eventually want the form to go to a new html page with the data that was in the form.
I think the issue is you don't have a submit button. Using your demo code, if I hit enter from the input field, I see the alert.
Try this:
$(document).ready(function() {
var newhtml = '<div class="nav-wrapper"> <form id="target"> <div class="input-field"><input id="search" type="search" required><input type="submit" value="search"></div></form></div>';
//replace nav bar with search bar
$("#replaceBar").replaceWith(newhtml);
$("#target").on('submit', function (event) {
alert("search submitted");
});
});
My codes was correct I just had the on submit event binded in a different function. I needed it to be right after the insert.
Now it works perfectly.
dynamically inserted elements need to use $().on();
if you don't know what is, search it in Jquery API.
your submit event bind before the event-target elements id inserted,
then the script can't work as you expected.
Try the event handler with document:
$(function(){
$(document).on('submit',function(e) {
e.stopPropagation();
if('target' === e.target.id) {
//to do here
}
});
});
Related
I have a little problem:
I have a modal that opens after some result search with ajax: it opens and show all requested results correctly.
On close, I need to empty another div with ID "results", empty an input with ID "search" and focus on it:
empty "results" is working
changing value of "search" to "" is also working
focus on "search" is not working
Here's my HTML:
<div class="col-sm-3">
<form action="" method="post" id="searchit">
<div class="input-group mar-btm">
<span class="input-group-addon"><i class="fa fa-search fa-lg"></i> Ricerca:</span>
<input type="text" id="search" tabindex="1" class="form-control" name="search" placeholder="Codice, EAN o Testo" />
</div>
</form>
</div>
<div class="col-sm-4" id="results"></div>
UPDATE:
jQuery:
$(".modal").on('hidden.bs.modal', function () {
$("#results").empty();
$("#search").val('');
$("#search").focus();
});
I also tried:
$(".modal").on('hidden.bs.modal', function () {
$("#results").empty();
$("#search").val('').focus();
});
and (is the only text input on this page):
$(".modal").on('hidden.bs.modal', function () {
$("#results").empty();
$("#search").val('');
$('input[type="text"]').focus();
});
In every case, empty() and val() are working properly but nothing is working with focus()! No error thrown in console...
I can't figure out what I'm missing/doing wrong!
Some help? Thanks in advance!
Problems with trying to use .focus() in an event handler usually stem from the event being handled also having an affect on focus. To get around that, I usually just wrap the .focus() call in a timeout:
$(".modal").on('hidden.bs.modal', function () {
$("#results").empty();
$("#searc").val('');
setTimeout(function() {
$("#searc").focus();
}, 10);
});
The timeout handler will run basically immediately after whatever triggered the event handler is all finished.
i am trying to use parsely.js on my html page to validate input box. currently this html page contains one input box and one submit button. the structure is created using bootstrap 3 and this page does not contain Form tag.
<div role='form'>
<div class="row form-group">
<div class="col-xs-3">
<label title="fullname">Full Name</label>
</div>
<div class="col-xs-4">
<input type="text" class='form-control' id="name" name="fullName" data-parsley-required="true" data-parsley-required-message="Please insert your name"/>
</div>
</div>
<input type="submit" class= "btn btn-danger"/> </div>
i am calling parsley.js like
function validateInput()
{
var handle = $("input[name='fullName']").parsley({
successClass: "has-success",
errorClass: "has-error",
classHandler: function (el) {
return $(el).closest('.form-group');//not working
},
errorsWrapper: "<span class='help-block'></span>",
errorTemplate: "<span></span>",
});
return handle.isValid();
}
on click of Submit button. it returns true/false correctly and create span tag also. but error classes are not applied. even data-parsley-required-message'Please insert your name' is not working.
when i put alert($(el)) or alert(el) it gives [object Object]. i think el should be the input object on which i am calling parsley function. but i am not able to get el.attr('id') or any other attribute. it returns undefined. i have also tried
//return el.closest('.form-group');//not working
//return el.$element.closest('.form-group)//not working
//return $(el).$element.closest('.form-group')//not working
I can not use Form tag as i am using this html structure in sharepoint content edtior web part.
A few things first:
Parsley allows you to bind it to a field, so you won't have a problem without the form element (see docs);
The classHandler function recieves an object of the type ParsleyField. With this object, you can access the input element with el.$element (for example: alert(el.$element.attr('id'));
I have made the following changes to your validateInput function:
<script type="text/javascript">
function validateInput() {
$("input[name='fullName']").parsley({
successClass: "has-success",
errorClass: "has-error",
classHandler: function (el) {
return el.$element.closest('.form-group'); //working
},
errorsWrapper: "<span class='help-block'></span>",
errorTemplate: "<span></span>",
});
// Returns true / false if the field has been validated. Does not affect UI.
//$("input[name='fullName']").parsley().isValid());
// validate field and affects UI
$("input[name='fullName']").parsley().validate();
}
</script>
With this code, the message is presented correctly, and the successClass and errorClass are appended to the div form-group.
See the following working jsfiddle
I have created a popup which allows users to edit a value then they can submit it again
Html:
<body>
<input id="submit" type="submit" value="Submit" data-theme="b" data-icon="check" data-rel="popup"/>
<div id="success" data-role="popup">
</div>
<div id="fail" data-role="popup">
<p>Fail</p>
</div>
</body>
jQuery:
$('#submit').click(function(){
var doStuff = true;
if(doStuff === true){
$("#success").empty();
$("#success").append('<p> <input type="text" value="' + doStuff + '" /> <input type="submit" id="popupConfirm" value="Submit" /> </p>');
$("#success").popup("open");
}else{
$("#fail").popup("open");
}
});
$('#popupConfirm').click(function(){
console.log("jhasgd");
});
Currently the click is not working at all that's why I have gibberish in the console.log and also I am not sure how to get the value of the entered input.
So my question is first how can I get the submit click to work and then output what they wrote?
fiddle of the code
$(document).on('click', '#popupConfirm', function(){
console.log("jhasgd");
});
Where are you adding the jQuery code at? If you are adding it all above the HTML, it might be trying to bind the #submit input before it exists in the DOM. Can you try to wrap the code in a document ready so it won't do the click binding before the DOM gets filled up.
$( document ).ready(function()
{
$('#submit').click(function(){
console.log("clicked the button");
});
});
Edit: I just saw the comment where you figured this out above. You didn't really have a code solution provided, so I will just leave this as is.
I have a popover with a form inside. And It is already out and ready for submission, here is the code for the popover
<div id="popover-head" class="hide">Add new subject</div>
<div id="popover-content" class="hide">
<form class="form-inline" id="pop-form" method="POST" action="../admin/module_add_subject.do">
<div class="form-group">
<!-- This input is what i'm talking about -->
<input type="text" name="subjectName" id="subject-name" required="required" pattern="^[\S\s]{3,25}[A-z]+$" title="Only accept alphabet characters and length is minimum of 3 and max of 25 " placeholder="Subject name.."/>
<button class="btn btn-primary" type="button" id="add-subject" ><i class="icon-white icon-ok"></i></button>
</div>
<p></p>
<p style="color:red" id="error-message"></p>
</form>
</div>
The input above I'm sure the regex is working. When I change the button to submitthe required is working perfectly fine but when I change it back to button then it is not working again.
The reason why my submit button is a type="button" because of this code:
$(document).on('click', '#add-subject', function(e) {
$.post('../admin/module_check_subject.do', { subjectName: $('#subject-name').val() },
function( data ) {
// if data from the database is empty string
if( $.trim( data ).length != 0 ) {
// hide pop-over
$('#popover').popover('hide');
// submit form
$('#pop-form').submit();
} else {
$('#error-message').text('Subject already exist.' );
}
}
})
.fail( function () {
bootbox.alert('Failed to check, please try again later.');
});
});
What I'm doing is on submit i'll check out first in my database if the input text in the textbox exist in the database, then if the text exist the database stop the submission of the form and display error at the p tag
By the form submission algorithm, validation is not performed when a form is submitted using the submit() method. The idea is, more or less, that when you submit a form with a script, your script should also carry out any checks deemed necessary.
Within your script, you can call the checkValidity() method to carry out the normal validation that would be performed if the form were submitted with a submit button. Note that it performs static validation only.
My HTML looks like this:
<form id="mainform" method="post">
<input type="text" class="required" name="receiver" />
<span id="clickMe">Click me</span>
<input type="submit">
</form>
And my JavaScript is as follows:
$(document).ready(function () {
$("#clickMe").click(function() {
$("input[name=receiver]").val("Clicked");
});
$("#mainform").validate({
submitHandler: function (form) {
alert("Success!");
return false;
}
});
});
Fiddle: http://jsfiddle.net/Y9RFt/2/
If you submit leaving the input empty, an error appears.
If you click the 'Click Me' span, the input is auto-filled, but the error remains until you submit the form. If you type something instead, the error disappears instantly.
Is there a way to emulate user input so that the error disappears on click?
Simply use the built-in .valid() method to force an immediate validation test of the form.
$("#clickMe").click(function () {
$("input[name=receiver]").val("Clicked");
$("#mainform").valid(); // <<-- Add this line to force a test
});
DEMO: http://jsfiddle.net/Y9RFt/8/
Got it. The solution is to simply blur the input:
$("input[name=receiver]").val("Clicked").blur();
Fiddle: http://jsfiddle.net/Y9RFt/7/