I am building a blog app that allows thread comments. The users can reply to other comments by clicking the "reply" button beside the particular comment. By doing that, a comment form will show up, and the user can type in his reply.
I am using jQuery to build this functionality, here is my code:
$(document).ready(function(){
$(".comment-reply").bind("click.a", function(){
// hide all forms
$(".comment-form-reply").hide();
// bind buttons with "click" events again, because one of them is unbinded
$(".comment-reply").bind("click.c", function() {
$(this).parent().siblings(".comment-form-reply").show();
});
// show the comment form for current item
$(this).parent().siblings(".comment-form-reply").show();
// unbind current button with "click" event to prevent multiple forms
$(this).unbind(".a");
});
$(".comment-reply").bind("click.b", function(){
event.preventDefault();
});
});
When I click the first and then the second button, it works well. But if I click the first button again, the two forms are displaying at the same time. I think there should be something wrong here, but I am not able to figure it out.
I can see one mistake. You forgot to define "event" as a parameter:
$(".comment-reply").bind("click.b", function(){
event.preventDefault();
});
Right way:
$(".comment-reply").bind("click.b", function(event){
event.preventDefault();
});
You are talking about a reply-button, so I am going to think you are talking about the other buttons with the same class ".comment-reply".
This example should do exactly what you are looking for with easy code.
$(document).ready(() => {
$(".comment-reply").on("click", evt => { // Use "submit" instead of "click" for form submition !
// Prevent site from updating (this is only needed for submit-buttons inside a form)
evt.preventDefault();
// Define varibles
var elmt = $(evt.target),
elmt_sib_c = elmt.parent().siblings(".comment"),
elmt_sib_cfr = elmt.siblings(".comment-form-reply"),
elmt_sib_exit = elmt.siblings(".comment-form-reply-exit");
if (elmt_sib_cfr.css("display") === "none") {
// Show reply-field
elmt_sib_cfr.show();
elmt_sib_exit.show();
} else if (elmt_sib_cfr.val() != "") {
// Hide reply-field
elmt_sib_cfr.hide();
elmt_sib_exit.hide();
//*//
console.log(
"Posted to DB at comment: '",
elmt_sib_c.text(),
"' with content of: '",
elmt_sib_cfr.val(),
"'"
);
//*//
} else if (elmt_sib_cfr.val() == "") {
elmt_sib_cfr.focus()
}
// Empty reply-field
elmt_sib_cfr.val("");
});
//
$(".comment-form-reply-exit").on("click", evt => {
// Define varibles
var elmt = $(evt.target),
elmt_sib_cfr = elmt.siblings(".comment-form-reply");
function hide () {
// Hide reply-field
elmt_sib_cfr.hide();
elmt.hide();
}
if (elmt_sib_cfr.val() == "") {
hide()
} else if (confirm("Are you sure?")) {
hide()
}
});
});
.comment-form-reply {
display: none;
margin-top: 10px;
margin-bottom: 5px;
}
.comment-form-reply-exit {
display: none;
margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="comment">This is comment '0'.</div>
<form action="/" method="post">
<input type="textfield" placeholder="My reply ..." class="comment-form-reply"><button type="button" class="comment-form-reply-exit">Abort</button>
<br>
<button type="submit" class="comment-reply">Reply</button>
</form>
</div>
<br><br>
<div>
<div class="comment">This is comment '1'.</div>
<form action="/" method="post">
<input type="textfield" placeholder="My reply ..." class="comment-form-reply"><button type="button" class="comment-form-reply-exit">Abort</button>
<br>
<button type="submit" class="comment-reply">Reply</button>
</form>
</div>
<br><br>
<div>
<div class="comment">This is comment '2'.</div>
<form action="/" method="post">
<input type="textfield" placeholder="My reply ..." class="comment-form-reply"><button type="button" class="comment-form-reply-exit">Abort</button>
<br>
<button type="submit" class="comment-reply">Reply</button>
</form>
</div>
<br><br>
<div>
<div class="comment">This is comment '3'.</div>
<form action="/" method="post">
<input type="textfield" placeholder="My reply ..." class="comment-form-reply"><button type="button" class="comment-form-reply-exit">Abort</button>
<br>
<button type="submit" class="comment-reply">Reply</button>
</form>
</div>
Related
I try to update this jquery script in pure js (with bootstrap 5). The goal is to not allow someone to click twice on the payment button. Sorry I am not very strong in js.
My goal is to have the same reaction that the jquery script.
I tried to follow the process on this page :
Disabling a button in vanilla JavaScript and in jQuery
Thank you
My current script
<form name="checkout_confirmation" action="http://............/Process" method="post" id="checkout_confirmation" role="form" onsubmit="return checkCheckBox(this)"><section class="checkout_confirmation" id="checkout_confirmation">
div class="text-end" id="process_button" class="processButton">
<button type="submit" data-button="payNow" class="btn btn-success">Confirmer la commande avec paiement</button> </div>
</div>
</form>
<script>
$('form[name="checkout_confirmation"]').submit(function() {
$('form[name="checkout_confirmation"] button[data-button="payNow"]').html('Confirm the payment').prop('disabled', true);
});
</script>
Now the script update
<script>
var button = document.getElementById('checkout_confirmation');
button.addEventListener('submit', function() {
alert('Confirm the payment');
});
button.disabled = false;
button.click(); // No output
button.prop("disabled", true);
</script>
setAttribute can be used in JavaScript to set the attribute of the button as disabled.
Element.setAttribute("disabled", true);
This can be used to disabled the button.
So when someone clicked on the submit button, you can disable the button till the data is processed.
Check the below demo code:
const btn = document.getElementById("submit-data");
btn.addEventListener("click", submitForm);
function submitForm(){
btn.setAttribute("disabled", true);
btn.innerText = "Submitting..";
let userName = document.getElementById("user-name").value;
console.log("Name: ", userName);
setTimeout(() => {
btn.removeAttribute("disabled");
btn.innerText = "Submit";
}, 3000);
}
<form type="POST">
<label for="user-name">Full Name</label>
<input type="text" id="user-name" placeholder="Your Full Name" />
<br /><br /><br />
<button id="submit-data">Submit</button>
</form>
You have two problems:
Submit events fire on form elements, not button elements.
getElementById gets an element by its id and neither your button nor your form has an id. (See this question).
Could you not use e.preventDefault() to stop the default behaviour of the button being pressed?
More can be read here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
I have a form that is using a function like
$(document).ready(function() {
$("#form1").submit(function() {
But I have 2 other forms that I'd like to use the same function if/when they submit, how would I write that?
$(document).ready(function() {
$("#form1").submit(function(),
$("#form2").submit(function(),
$("#form3").submit(function() {
Thanks
If I understand, you want to share a function for various submit event handlers. This is fairly simple:
function submitHandler() {
// handler stuff here.
}
$(document).ready(function() {
$("#form1").submit(submitHandler);
$("#form2").submit(submitHandler);
$("#form3").submit(submitHandler);
}
and alternative, if you want to handle all forms, is to specify which forms in the jquery selector. You can do this for all forms on the page:
$(document).on('submit','form', function() { });
or, if you just add a class name to the forms you want to use it on:
$(document).on('submit','.formclass', function() { });
You should be able to just do this:
$("#form1, #form2, #form3").submit(function() {
formid = this.id;
console.log('Processing form [' +formid+ ']');
...etc...
Any of the specified IDs will trigger that submit function.
Using the formid var, you can fine-tune any form-specific mods within the function.
You can pass the id of the form to submit them separately.
This code will allow you to have as many forms as you like without having to update the JS.
function submitForm(id) {
$("#" + id).submit(function(e) {
e.preventDefault();
for (let i = 0; i < e.target.length - 1; i++) {
console.log(e.target[i].name, e.target[i].value);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<input name="name">
<button onClick="submitForm('form1')">Submit</button>
</form>
<form id="form2">
<input name="name">
<button onClick="submitForm('form2')">Submit</button>
</form>
<form id="form3">
<input name="name">
<button onClick="submitForm('form3')">Submit</button>
</form>
By JQuery you can use the below function $("form").submitNow() with any form element.
$.fn.submitNow = function() {
var form = $(this);
// handle form element
console.log(this.id, this.action);
$(this).submit();
}
//use it
$("form").submitNow();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="./action1" id="action1">
<input type="submit" value="form1" />
</form>
<form action="./action2" id="action2">
<input type="submit" value="form2" />
</form>
<form action="./action3" id="action3">
<input type="submit" value="form3" />
</form>
I have several forms on my profile page. Each form has its own submit button. When a user clicks the submit button, I want the button to disappear and show a spinner.
That works fine. The issue that I am running into, is that if the user forgets to fill-out a required field, the button does not return visible. The spinner stays visible. And the page would have to be reloaded.
Jquery is not intercepting the form submission (though I am open to that if it will fix the issue), it is only toggling the spinner and button visibility.
Any help?
$("#profile-loading").hide();
$("#social-loading").hide();
$(document).ready(function () {
$("#btn_profile").on("click", function (e) {
$("#profile-loading").show();
$("#btn_profile").hide();
checkForm('#formProfile', "#btn_profile", "#profile-loading");
});
$("#btn_social").on("click", function (e) {
$("#social-loading").show();
$("#btn_social").hide();
checkForm('#formSocialMedia', "#btn_social", "#social-loading");
});
});
//Check the passed in form and toggle the buttons and the loading spinner
function checkForm($formid, $buttonid, $spinnerid) {
var emptyFields = $('#formProfile .required').filter(function () {
return $(this).val() === "";
}).length;
if (emptyFields === 0) {
console.log("no emptyFields");
} else {
console.log("emptyFields");
return false;
}
//I tried looping through each form field, but can't seem to get the form targeted.
// $($formid + '.required').each(function () {
// console.log("checkForm");
//
// var self = $(this)
// if (self.val() === '') {
// // empty
// console.log("empty");
// } else {
// // not empty
// console.log("NOT empty");
// }
// });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="somelink" id="formProfile">
<input id="name" name="name" type="text" required="required">
<input id="url" name="url" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="profile-loading"></i>
<button id="btn_profile" type="submit">Save Changes</button>
</form>
<form method="post" action="someotherlink" id="formSocialMedia>
<input id="facebook" name="facebook" type="text" required="required">
<input id="instagram" name="instagram" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="social-loading"></i>
<button id="btn_social" type="submit">Save Changes</button>
</form>
There are several issues with your code, but the most important one is that you are retrieving required form elements using a required class, which does not seem to be used in your html. Instead, you can retrieve required form elements using something like
$('#formProfile [required]')
which returns all subelements of formProfile which have the required attribute. You have another issue in that the id of the form is hard-coded. Instead of hard-coding it, use the variable $formid.
$($formid + ' [required]')
Try reordering your scripts, do validation first and check if it's pass. Make sure the checkForm returns true if valid.
$("#btn_profile").on("click", function (e) {
if (checkForm('#formProfile', "#btn_profile", "#profile-loading")) {
$("#profile-loading").show();
$("#btn_profile").hide();
}
});
$("#btn_social").on("click", function (e) {
if (checkForm('#formSocialMedia', "#btn_social", "#social-loading")) {
$("#social-loading").show();
$("#btn_social").hide();
}
});
I have 2 divs:
<div class="lobsummary">
<input type="submit" name ="sbmtbtn">
<input type="submit" name ="sbmtbtn">
</div>
<div class="applicationsummary">
</div>
I want to show applicationsummary when sbmtbtn is submitted so I used the below script:
$('.lobsummary input:submit').submit(function (event) {
$('.applicationsummary').show();
$('.lobsummary').hide();
});
But its not working.
EDIT: The divs are enclosed in <% Html.BeginForm("Index", "Home"); %> which I am using to pass values to my controller from the view.
Use event.preventDefault() it stops the default action
$('.lobsummary input[type=submit]').click(function (event) {
event.preventDefault();
alert($(this).index() + 1);
$('.applicationsummary').show();
$('.lobsummary').hide();
});
#Rajaprabhu Aravindasamy is right,use submit() over a form:
$("form").submit( function () {
return false;
} );
HTML on the client side will be like:
<div class="lobsummary">
<form action="/"method="post">
<input type="submit" name ="sbmtbtn">
</form>
<form action="/"method="post">
<input type="submit" name ="sbmtbtn">
</form>
</div>
<div class="applicationsummary">
</div>
Just use click() to test your jquery selection:
$('.applicationsummary').hide();
$(".lobsummary form:eq(0)").click(function () {
alert(1)
$('.applicationsummary').show();
});
$(".lobsummary form:eq(1)").click(function () {
alert(2)
$('.applicationsummary').hide();
});
Then replace the click to submit.
When the form was submitted, it reloaded the whole page and that's why it was not hiding because it was going back to its default view. So I used if statements in my view to hide the forms.
html:
<script src="http://zurb.com/playground/javascripts/plugins/jquery.textchange.min.js"></script>
<form>
<input type="text" name="comment" id="comment" placeholder="Comment" maxlength="140" value=""/>
<div id="charactersLeft"></div>
<input type="submit" id="commentButton" data-icon="edit" data-inline="true" data-mini="true" data-theme="b" value="Send" disabled="disabled"/>
</form>
<div id="actionList">
</div>
js:
$('#comment').bind('hastext', function () {
$('#commentButton').button('enable');
});
$('#comment').bind('notext', function () {
$('#commentButton').button('disable');
});
$('#comment').bind('textchange', function (event, previousText) {
$('#charactersLeft').html( 140 - parseInt($(this).val().length) );
});
$('#commentButton').click(
function(){
$('#actionList').prepend('<p class="item">' + $('input[name=comment]').val().trim() + '</p>');
$('#commentForm').each (function(){ this.reset(); });
//document.getElementById('commentForm').reset();
$(this).button('disable');
}
);
On Fiddle its works another, that on my machine. So, test local. The problem is: when I write a comment, than I click on the button, comment apears in #actionList, the button blocked. Nice. But. If I want to write a new comment, the button will be disabled. I have text in input, but I cant click button. I deleted my new text in input, and than I can write something and button finally enabled.
Its very strange, how to fix it? Thanks.
I added the line, to remove comment once posted:
$('#comment').val("");
I also replaced your hastext and notext functions with this code, added in the textchange function:
var tb_value = this.value;
if (tb_value == "") {
$('#commentButton').button('disable');
} else {
$('#commentButton').button('enable');
}
See the Fiddle.