Jquery function not fired (html injected in second moment) [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
Sorry for no-too-much clear title.
I'm using Twitter Bootstrap Modal to edit some record.
<a class="contact" href="#" data-form="/edit/models/sms/{{ #value['fields']['id'] }}" title="Edit">
<span class="fa-stack fa-lg">
<i class="fa fa-square-o fa-stack-2x"></i>
<i class="fa fa-pencil fa-stack-1x"></i>
</span>
</a>
And this is the javascript code that open the Modal:
$(".sms-model").click(function(ev) { // for each edit contact url
ev.preventDefault(); // prevent navigation
var url = $(this).data("form"); // get the contact form url
$("#smsModelModal").load(url, function() { // load the url into the modal
$(this).modal('show'); // display the modal on url load
});
$("#smsModelModal").modal('show'); // display the modal on url load
return false; // prevent the click propagation
});
Finally this is the form injected inside the modal:
<div class="modal-body">
<form role="form" method="post" class="sms-model-form" action="{{ #SERVER.REQUEST_URI }}">
<fieldset>
<legend class="sr-only">Edit</legend>
<input type="hidden" name="edit_id_model" value="{{ isset(#sms_model) ? #sms_model[0]['fields']['id']['value'] : '' }}" />
<div class="form-group">
<label for="title">{{ #lng_label_sms_title }}</label>
<input type="text" class="form-control required-field" name="title" value="{{ isset(#sms_model) ? #sms_model[0]['fields']['title']['value'] : '' }}"/>
</div>
<div class="form-group">
<label for="text">{{ #lng_label_sms_text }}</label>
<textarea class="form-control" name="text" class="required-field">{{ isset(#sms_model) ? #sms_model[0]['fields']['text']['value'] : '' }}</textarea>
</div>
<button type="submit" class="btn btn-white pull-right">
<i class="fa fa-plus-circle"></i> {{ isset(#sms_model) ? #lng_btn_edit : #lng_btn_add }}
</button>
<input type="submit" class="btn btn-primary" value="Test" />
</fieldset>
</form>
</div>
Everything functions as a charme. Now I would submit the form via AJAX.
So I'm adding this:
$('.sms-model-form').on('submit', function(e) {
console.log('test on submit....');
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: this.action,
data: $(this).serialize()+'&ajax=TRUE',
context: this,
success: function(data, status) {
$('#smsModelModal').html(data);
}
});
return false;
});
But form is submitted via regular mode, and not via AJAX. I.e. I don't have neither the event logged in console.
I'm thinking that this is because the form is injected in a second moment in the page and not at
$(document).ready(function() {
Am I right? How I can solve my issue?

You almost certainly need to set up your event handler via delegation:
$(document).on('submit', '.sms-model-form', function(e) {
That attaches a handler at the root of the DOM to catch bubbling "submit" events. Because you're adding your modal dialog content after your code runs, if you do it your way the code will simply have no effect; the ".sms-model-form" selector will match nothing, so no event handler will be attached anywhere.
Using the above form of .on(), you ensure that events involving DOM substructures added dynamically will still be handled as you desire them to be.

Related

Ajax refreshes the whole page instead of a particular part

Net web services. The following code is attached to my master page using a JS. When I run the ajax call, it seems like at the end of success function, it refreshes the whole page. Rather than some particular part. I have tried using both ways, form + input submit, and normal button with click function.
$.ajax({
url: 'service url',
data: { LookupParameter: somevariable },
method: 'POST',
dataType: 'xml',
asynch: false,
cache: false,
success: function (data) {
var xmldata = $(data);
//dom manipulation code
},
error: function (e) {
}
});
Master Page
following code is embedded inside body tag. but not in content placeholder.
<form itemscope itemtype="http://schema.org/LocalBusiness" id="form1" runat="server">
<span class="input-group-addon borderRadiusZero" id="basic-addon1">
<span class="glyphicon glyphicon-question-sign"></span>
</span>
<Input ID="txt_lookup_pincode" type="number" class="form-control" min="111111" max="999999" placeholder="Enter Your Pincode" />
<span class="input-group-btn ">
<button id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button>
<input id="LookupServices" class="btn btn-primary borderRadiusZero" style="height:100%;" type="submit" value="submitM" />
</span>
The issue may be because of this line
<button id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button>
The button type is not defined here. In this case the default type that is submit will be applied.
Define the button type as button
<button type = "button" id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button>
If your JavaScript function with the Ajax call is included in the onclick handler of your button, it should return false to prevent the default action of the button:
<button id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas(); return false;" style="height:100%;">Submit</button>
You can add to the button the type "button" to suppress the default behavior
<button type="button" id="LookupServicesa" class="btn btn-primary borderRadiusZero" onClick="HomeCheckDeliverableAreas();" style="height:100%;">Submit</button
put the dom elements which you want to refresh after the ajax success in another div which is outside the form and do the manipulations to that div. Hope this helps!

jquery to disable buttons on submit/click in forms and links

In my rails app I have buttons that submit information to the server. Some buttons are part of a form and some are not. I'm looking for a way to apply my jquery, which disables the buttons after click, to both.
Here is my current jquery:
$('.btn-disabler').on('click', function() {
$(this).append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
$(this).find('.btn-label').addClass('invisible');
});
This code adds an icon disables the button and makes the text invisible. I've extended the disable function to work on anchor tags as explained here https://stackoverflow.com/a/16788240/4584963
An example link:
<a class="btn btn-success btn-disabler" rel="nofollow" data-method="post" href="/approve?id=10">
<span class="btn-label">Approve</span>
</a>
An example form:
<form class="simple_form well" novalidate="novalidate" id="new_user" action="/" accept-charset="UTF-8" method="post">
<div class="form-group">
<input class="string optional form-control" placeholder="First name" type="text" name="user[first_name]" id="user_first_name">
</div>
<div class="form-group">
<input class="string optional form-control" placeholder="Last name" type="text" name="user[last_name]" id="user_last_name">
</div>
<div class="form-group">
<input class="string email optional form-control" placeholder="Email" type="email" name="user[email]" id="user_email">
</div>
<div class="form-group">
<input class="password optional form-control" placeholder="Password" type="password" name="user[password]" id="user_password">
</div>
<div class="form-groups">
<input class="password optional form-control" placeholder="Retype password" type="password" name="user[password_confirmation]" id="user_password_confirmation">
</div>
<button name="button" type="submit" class="btn btn btn-primary btn-disabler">
<span class="btn-label">Submit</span>
</button>
</form>
My jquery above does not work for the form. In the form on click, the button changes but there is no submission. To get the jquery to work for the form I need to change it to this:
$('.signup-form').on('submit', function() {
$(this).find('.btn-disabler').append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
$(this).find('.btn-label').addClass('invisible');
});
How can I consolidate this to apply to both links and form submit buttons? Seems like my problem stems from links need the click event and the form needs the submit event.
You can use jQuery is() to check parent of current button object is form or not in order to submit the form:
$('.btn-disabler').on('click', function() {
$(this).append("<i class='fa fa-spinner fa-pulse btn-loader'>").disable(true);
$(this).find('.btn-label').addClass('invisible');
if ($(this).parent().is("form")) $(this).parent().submit();
});
do you try this using the id of the form like
$('#new_user').on('submit' ...
or with the form element
$('form').on('submit' ...
Think of the submit button as an extension of a form submit event. If you disable the form submit button, the form submit event is disabled. What you can do is add the class to the form, and then in your jQuery code you can assign specific rules. something like this..
So, using this HTML:
<form class="disabler">
<button type="submit"><span>Label</span></button>
</form>
<span>Label</span>
<button class="disabler"><span>Label</span></button>
Use this javascript:
$('.disabler').each(function(e){
if(this.nodeName == "A"){
// this is a hyperlink...
// apply css class
$(this).on('click', function(){
//some action
});
} else if (this.nodeName == "BUTTON") {
//this is a button outside of a form
// disable and add css class
$(this).on('click', function(){
//some action
});
} else if (this.nodeName == "FORM") {
$(this).on('submit', function(){
$(this).find('button[type="submit"]')
.append("<i>Loading</i>")
.disable();
});
}
});
You can probably refactor this down more, but i think you should pay attention to nodeName when you're trying to apply different rules to each of these components.
I hope this answers your question.

Jquery form being submitted twice

I have a really strange problem. My Jquery based form appears to be submitting its self twice.
It only happens when I use the following code to submit my form:
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
When I use the following, I do not get the double submit:
<input type="submit" value="Transfer" class="btn btn-success dark" id="transfer-button"/>
Here is the code in context:
FORM:
<form class="form-horizontal hidden" id="transfer-form" novalidate>
<fieldset>
<div class="control-group">
<div> </div>
<div class="controls">
<button class="btn dark"><i id="transfer-spin" class="fa fa-cog"></i> Transfer...</button>
</div>
</div>
</fieldset>
</form>
And the JQuery code:
$('#transfer-form').submit(function()
{
event.preventDefault();
//run some error checks
if (messageArray.length !== 0)
{
//Return errors
} else {
$('#transfer-button').prop('disabled', true);
$('#transfer-spin').addClass('fa-spin');
var url ='/api/transfer';
$.ajax({
//Do the ajax call...
You need to pass the event as parameter in submit:
$('#transfer-form').submit(function(event)
Your submit function needs to receive the event object
function (event) {
...
I believe you have to specify the event variable in the function, with that you can prevent default behavior.
$('#transfer-form').submit(function(event)
{
event.preventDefault();
...
}

redirect to another page using onsubmit or action?

I am trying to direct to another page on particular event occurrence ...This is my code..but it does not direct to another page but the JavaScript code works...
<form class="list-group-item" method="get" onsubmit="action='Search.jsp'; myFunction('name');return false;" >
<input type="hidden" name="item" value="<%=1%>">
<i class="fa fa-arrow-circle-right fa-fw "></i> <span onsubmit="action='Search.jsp'" onclick="action='Search.jsp';document.getElementById('div1').style.display = 'block';setValue('Subject')" style="margin-left:1%">Subject </span>
<span class=" text-muted small" onclick="document.getElementById('div1').style.display = 'block';setValue('Subject And')" style="margin-left:40%"><em> And <i class="fa fa-angle-down "></i></em>
</span>
</form>
First I tried action="search.jsp" outside onsubmit but that didn't work..I am new to all this and I don't know what to do?
Add an button inside <form> tag
<input type="submit" value="Submit">
Add action attribute in form tag
action="Search.jsp"
Whenever you click Submit button, the page will be redirected to Search.jsp
1) If you simply want to get it redirected to Search.jsp after form submission, remove all crap JS code from your form and add a simple action attribute in form tag.
2) Action attribute behaves as redirect if you submit the form.
3) Writing JS code within HTML Tags is a bad convention. Always write JS code within <script>..</script> blocks or a different JS file and then include it.
<form class="list-group-item" method="get" action="Search.jsp" >
<input type="hidden" name="item" value="<%=1%>">
...
...
</form>
OR
You can ajaxify your code (meaning submit the form through ajax and then redirect).
<form class="list-group-item" method="get" action="Search.jsp" name="search" >
<input type="hidden" name="item" value="<%=1%>">
...
...
</form>
<script>
$(function(ev){
ev.preventDefault();
$("form:[name='search']").on("submit", function(){
var form = $(this);
var data = form.serialize();
var action = form.attr("action");
$.get(action, data)
window.location.replace("http://stackoverflow.com");
});
});
</script>
Simply return true from the myFunction and use <input type="submit"> to submit the form.
Sample code: (read inline comments)
<script type="text/javascript">
function myFunction() {
/* return false in case of validation fail */
alert("Hi");
return true;
}
</script>
<form class="list-group-item" action="Search.jsp" method="get"
onsubmit="return myFunction()">
<!-- other fields -->
<input type="submit" value="Submit" />
</form>

Error sending a form via AJAX

I am very new to jQuery and I'm looking for an explanation as to why this code does not seem to work. I think it is something with the "action" not sure. Can someone help me understand my mistake here. thanks
<script src="/jquery.validationEngine.js"></script>
<script>
$("#contact_body").submit(function(e) {
e.preventDefault(); // Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
if ($("#contact_body").validationEngine('validate')) {
//Post Data to Node Server
$.post(
$this.attr("action"), // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) { /** code to handle response **/ },
"json" // The format the response should be in
);
//Notify User That the Email Was Sent to the Server & Thanks!
//$('#contactThanksModal').modal('show');
$('#contactModal').modal('hide');
alert("success");
}
else {
//handle Invalid Email Format Error
alert("error");
}
});
</script>
<!--pop up contact form -->
<div id="contact" class="modal hide fade in" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal">x</a>
<h3>Send us a message</h3>
</div>
<div class="modal-body">
<form id="contact_body"class="contact_body" name="contact_body" action="/contact">
<label class="label" for="form_name">Your Name</label><br>
<input type="text" name="form_name" id="form_name" class="input-xlarge"><br>
<label class="label" for="form_email">Your E-mail</label><br>
<input type="form_email" name="form_email" class="input-xlarge"><br>
<label class="label" for="form_msg">Enter a Message</label><br>
<textarea name="form_msg" class="input-xlarge"></textarea>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="submit">
Nah.
</div>
<!-- <div id="thanks"><p><a data-toggle="modal" href="#contact" class="btn btn-primary btn-large">Modal powers, activate!</a></p></div> -->
You need to wrap your JQuery scripts in a
$(document).ready(function() {
...your_code_here...
});
This will then wait for the whole document to load before trying to attach events to objects.
Without this you may be trying to bind events to objects that have yet to be "created".
You need to put your code in a document ready handler:
<script src="/jquery.validationEngine.js"></script>
<script>
$(function() {
$("#contact_body").submit(function(e) {
// your code...
});
});
</script>
Your code is currently trying to add the submit() handler before the element exists in the DOM.

Categories

Resources