On submit of class post_alternate_category_name I need to make value of input element alternate_category empty and I need to set the text of label .ermsg as saving... The code which I have written is not working:
<form method="POST" class="form-horizontal post_alternate_category_name">
<div class="control-group">
<label class="control-label">Alternate name</label>
<div class="controls">
<input class="m-wrap large alternate_category" name="alternate_category" type="text" value="">
<button type="submit" class="btn blue">Add</button>
<label class="ermsg" style="color: red"></label>
<input type="hidden" name="category_id" value="1">
</div>
<input type="hidden" name="_token" value="Jl3DOrLd0clH5cv17I5JQumqFtJzV8uNjblIZGu3">
</div>
</form>
$('.post_alternate_category_name').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "someurl",
data: "somedata",
beforeSend:function() {
$(this).children('.control-group').children('.controls').children('.ermsg').val('Saving');
$(this).find('.ermsg').html("");
},
success: function(response) {
$(this).children('.control-group').children('.controls').children('input[name="alternate_category"]').val('');
}
});
});
You can use
.find() function to get all children inside element.
jQuery find
Instead of using multiple ".children()" methods, you can reset and update values directly. See code below. Place it anywhere you like.
$('.post_alternate_category_name').on('submit', function(e) {
e.preventDefault();
$('input[name=alternate_category').val('');
$('label.ermsg').text(''Saving...);
)};
a) I need to make value of input element "alternate_category" empty.
$('input[name="alternate_category"]').val('');
b) I need to set the text of label ".ermsg" as "saving.."
$('.ermsg').html("saving..");
Related
I have a headless WordPress site. I'm working on the event handler to submit the contact form. I'm using Contact Form 7. I've tried using vanilla JS, I'm using jQuery here because it seems like a better option, and I'm losing my mind.
Essentially, the form submits but the fields do not clear. I've tried form.reset() in JS, $('#formid')[0].reset() in jQuery, and the code below. I don't know why this isn't working and the result is really suboptimal. Any ideas?
I will fully admit that I am more comfortable working in javascript than jQuery so I might be missing something obvious.
If I don't have the iframe set as the form target, the page redirects to a white page with JSON data. Am I missing something about event.preventDefault()? It's not working the way it should, and has in my experience.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(this)
}).done(resetForm());
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
There's several separate issues:
.done(resetForm()) is incorrect as it immediately calls resetForm() and sets the returned value from that call as the event handler.
You need to send the $form argument in the resetForm() method call, so provide a full function block to the done() handler, including that argument
When sending a FormData object in a jQuery AJAX call you need to set processData and contentType to false so the data is encoded correctly.
jQuery does not have :tel and :file pseudo selectors. Instead you can use :input to select all input, textarea and select elements to reset their values.
Changing the type of the date control to text and then back to date is not necessary, even without the above point.
$(document).ready(function() {
const $form = $('#formElem').on('submit', function(e) {
e.preventDefault();
let data = new FormData(this);
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: data,
contentType: false,
processData: false
}).done(function() {
resetForm($form)
});
})
function resetForm($form) {
$form.find(':input').val('');
// alternatively to reset the form to original state, not wipe all fields use this
// $form.get(0).reset();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback" id="formElem" name="contactForm" method="post" class="contact__form" target="formtarget">
<h3 class="contact__form--heading">Contact</h3>
<p class="contact__form--paragraph">Currently operating out of Minot, North Dakota. Soon to be in South Korea!</p>
<input id="your-name" class="contact__form--input" type="text" name="your-name" placeholder="Name">
<input id="your-email" class="contact__form--input" type="text" name="your-email" placeholder="Email">
<input id="your-tel" class="contact__form--input" type="tel" name="your-tel" placeholder="Phone">
<input id="preferred-date" class="contact__form--input" placeholder="Select session date" type="date" name="preferred-date">
<textarea id="your-info" class="contact__form--input" placeholder="Tell me about yourself!" name="your-info"></textarea>
<textarea id="services" class="contact__form--input" placeholder="What services are you interested in booking?"></textarea>
<textarea id="how-heard" class="contact__form--input" placeholder="How did you hear about my business?" name="how-heard"></textarea>
<input id="btnSubmit" class="contact__form--input btn-contact" type="submit" name="submit">
<div id="messageArea"></div>
<iframe class="formtarget" name="formtarget"></iframe>
</form>
In your code you are calling resetForm and assigning what it returns to the done event handler. It is not calling that function when done is called.
You also are not passing the form reference to the function. So you will have an error message in your console.
$(document).ready(function() {
$('#formElem').on('submit', function(event) {
var form = this;
event.preventDefault();
let request = $.ajax({
url: "https://api.chloemedranophotography.com/wp-json/contact-form-7/v1/contact-forms/54/feedback",
type: "post",
data: new FormData(form)
}).done(function () { resetForm(form); });
})
function resetForm($form) {
$form.find('input:text, input:tel, input:file, select, textarea').val('');
$('datePicker').val('').attr('type', 'text').attr('type', 'date');
}
});
I am trying to insert some HTML before a divider class="replydivider" using insertBefore() but I can't get it to work. This is my code:
<div class="col-sm-12 mb-2 replydivider">
<div class="row">
<div class="col-sm-2 offset-1">
<img src="/assets/uploads/user/<?=$_SESSION['userImage'];?>" class="border rounded-circle comment-user-img mr-3">
</div>
<div class="col-sm-8 rounded form-inline">
<form method="POST" class="form-group reply-form">
<input type="text" name="comment" class="form-control mr-2" placeholder="Reply here" required>
<input type="hidden" name="postId" value="<?=$id?>">
<input type ="hidden" name="replyId" value="<?=$row['commentId'];?>">
<input type="submit" class="btn-sm btn-primary" value="Reply">
</form>
</div>
</div>
</div>
The issue I'm having is it has to be inserted before the div relative to the form that is submitted as there will be many replydividers and forms on the page.
I've tried the following and countless variations but can't get it to work:
$(this).closest('.replydivider').before(data);
$(this).closest('div').find(".replydivider").before(data);
$(this).closest('form').find(".replydivider").before(data);
$(data).insertBefore('.replydivider');
Any guidance would be appreciated.
EDIT:
This is my jquery function:
$(function () {
$('.reply-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/comment/addComment',
data: $(this).serialize(),
success: function (data) {
alert('test');
var test = "<p>Sample data</p>";
$(this).closest('.replydivider').before(test);
}
});
$(this).closest('form').find("input[type=text]").val("");
});
});
Interestingly, if I put the $(this).closest('.replydivider').before(test); line outside the ajax call it works, but not inside it. I put the alert there to test it was returning successful and it is.
.ajax()
The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.
If you want this in the callbacks to be the element that received the event then set the context property of Ajax like:
.......
context:this,
success: function (data) {
.......
I have the following input box which takes input from barcode scanner.
<form class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ url('updateInvoice') }}" id="invoice_update">
<div class="form-group m-form__group">
<label for="exampleInputEmail1">Search by item name or barcode</label>
<input type="text" autofocus class="form-control m-input" id="productSearch" placeholder="Item name">
</div>
<button type="submit" name="pdf" class="btn btn-success">Update & print
</button>
</form>
After getting the input from barcode it does following operation (from the input it checks value from database and add to row)
$( "#productSearch" ).change(function(event) {
event.preventDefault();
$.ajax({
type: "get",
context: this,
url: "{!! asset('searchByProductName') !!}",
dataType: 'json',
data: { name:this.value },
success: function(response)
{
if ($('#' + response.id).length !== 0)
{ $(this).val("").focus(); return false; }
var markup = "<tr id="+response.id+"><input type='hidden' name='product_id[]' value="+response.id+"><td><i class='flaticon-delete-1 delete-row' onclick='deleteRow(this)'></i></td><td>"+response.product_name+"</td><td>"+response.product_unit_price+"</td><td><input type='text' name='quantity[]' class='quantity' value='1'></td><td class='total'>"+response.product_unit_price+"</td><td>"+response.notes+"</td></tr>";
$("table tbody").append(markup);
$(this).val("").focus(); return false;
}
});
});
But the problem the form get auto submit ie, i can't add more than one value in the table. How do i prevent the form automatic submit so that more that one input can be taken with the above ajax code?
I'm not sure if the barcode scanner put the "enter key", but how about this one?
$("#form-id").on("submit", function(e) {
if ($("#input-id(productSearch)").is(":focus")) {
e.preventDefault();
}
});
IMO, the easiest way is to add a hidden input
<input type="hidden" />
browser will auto submit if there is one input in a form.
I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}
I'm currently trying to make a ajax comment function work once a user clicks "open comments".
Currently I'm getting data back from my php script and the status of the ajax call is "200 OK" so it definetely works but I'm just unable to get the correct value for the current comment which has been clicked on in order to post it to the php script.
What I'm asking is how do I get the value of the ".posted_comment_id" class and then how do I load the data which is returned into the ".commentView" class?
jQuery/AJAX:
$(".closedComment").click(function(){
var $this = $(this);
$this.hide().siblings('.openComment').show();
$this.siblings().next(".commentBox").slideToggle();
$.ajax({
type: "POST",
url: "http://example.dev/comments/get_timeline_comments",
data: {post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").val()},
dataType: "text",
cache:false,
success:
function(data){
$this.closest(".commentView").load(data);
}
});
return false;
});
HTML:
<div class="interactContainer">
<div class="closedComment" style="display: none;">
open comments
</div>
<div class="openComment" style="display: block;">
close comments
</div>
<div class="commentBox floatLeft" style="display: block;">
<form action="http://example.com/comments/post_comment" method="post" accept-charset="utf-8">
<textarea name="comment" class="inputField"></textarea>
<input type="hidden" name="post" value="13">
<input type="hidden" name="from" value="5">
<input type="hidden" name="to" value="3">
<input type="submit" name="submit" class="submitButton">
</form>
<div class="commentView"></div>
<div class="posted_comment_id" style="display:none;">13</div>
</div>
</div>
Replace .val by .html or .text. This will return the innerHTML of the element.
data: {
post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").text()
}
You might need to convert the string to an integer to make it work.
If the query selector fails, this selector might do the job instead:
$this.parent().find(".posted_comment_id")
To add the returned data on your webpage, use the success handler. Here's an example of how it's done:
success: function(json) {
// Parse your data here. I don't know what you get back, I assume JSON
var data = JSON.parse(json),
content = data.whatever_you_want_to_print;
// Assuming your selector works, you put in in the element using .html
$this.closest(".commentView").html(content);
}
});
You probably want to do something like:
$(this).parents('.interactContainer').find(".posted_comment_id").text()