Jquery form element access - javascript

I'm new to jquery and trying to do the following:
I have a form:
<form method="POST" class="add-product" >
...
<label name="message"></label>
...
</form>
And script:
$(document).ready(function() {
$(".add-product").submit(function(e) {
e.preventDefault();
var form = this;
$.ajax({
type: "POST",
url: "/product/add/",
data: $(this).serialize(),
success: function(data) {
$(form.elements["message"]).html(data.message);
}
});
});
});
I'm trying to update label with message, but it doesn't work. Seems that I have some mistake in syntax:
$(form.elements["message"]).html(data.message);

The issue is because the label does not appear in the form.elements collection. Instead you need to select it directly:
$(".add-product").submit(function(e) {
e.preventDefault();
var form = this;
// inside the AJAX callback...
var data = {
message: 'Foo bar'
}
$(form).find('label[name="message"]').html(data.message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" class="add-product">
<label name="message"></label>
<button>Submit</button>
</form>

You used wrong jquery selector, try it:
$('label[name="message"]').html(data.message);
hope this help;

Try using the selector:
$("form.add-product label[name='message']").html(data.message)
You can read more about jQuery Attribute selector's here. https://api.jquery.com/attribute-equals-selector/
If you have more than one label on the page with the attribute name='message' then the above won't work.

Related

Ajax disable the form fields

I use the following Ajax script to post data and to disable the send-button and the form fields. At the moment only the submit button disables on click, but I want all the fields to be disabled.
So that's why I added: var compl_form = $('form#updateBeschikbaarheid'); and compl_form.attr("disabled", "disabled");
But that won't work.
<script type="text/javascript">
$(document).ready(function(){
$("form#updateBeschikbaarheid").submit(function(event) {
event.preventDefault();
var formData = $(":input,:hidden").serialize();
var btnSubmit = $('#uploadenFormSend');
var compl_form = $('form#updateBeschikbaarheid');
$.ajax({
type: "POST",
url: "beschikbaarheid.insert.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
btnSubmit.val("Wacht op goedkeuring"); // put your normal text
btnSubmit.attr("disabled", "disabled");
compl_form.attr("disabled", "disabled");
}
});
});
});
</script>
Form:
<form method="post" id="updateBeschikbaarheid" name="updateBeschikbaarheid">
<input type="time" name="zaterdag_van" id="zaterdag_van" value="">
<input type="time" name="zaterdag_tot" id="zaterdag_tot" value="">
<input type="submit" class="button-pink" value="<?php echo $button_text; ?>" id="uploadenFormSend" name="uploadenFormSend">
</form>
You cannot disable a form like that, but you can disable the inputs:
$(':input').prop('disabled', true);
Or in older versions of jQuery
$(':input').attr('disabled', 'disabled');
.prop()
.attr()
EDIT: based on your question in the comments, you can leave a select box enabled like this:
$(':input').not('select').attr('disabled', 'disabled');
compl_form.prop("disabled", true);
try this.

JavaScript jQuery issue with submit button

I have a problem. I think it's because of the rendering but I don't know because that topic is new to me.
Okay, I have a simple form:
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Now i want to catch that submit using jQuery like:
$('[type=submit]').submit(function(e) {
e.preventDefault();
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
});
okay, that code works really good. It does what it should do. But, If I want to send a second request, the submit button doesn't work anylonger as intended. It tries to send the form using the default-action although I prevnted that - at least that's what I thought.
I did use google but I don't even know how to explain my problem.
Hopefully someone can help me, thanks a lot!
Greetz
Instead of .html() you can use:
.clone(true): Create a deep copy of the set of matched elements.
.replaceWith(): Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
The event must be click if attached to submit button or submit if attached to the form.
The snippet:
$('[type=submit]').on('click', function (e) {
e.preventDefault();
var formHtml = $(this).closest('form').clone(true);
$.ajax({
dataType: "json",
url: 'https://api.github.com/repos/octocat/Hello-World',
beforeSend: function (xhr) {
$('form').html("sending mail");
},
success: function (data) {
console.log('Success');
$('form').replaceWith(formHtml); // I think here's the problem...
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Use $(document).on("click", "[type=submit]", function (e) { for dynamically created ekements instead of $('[type=submit]').submit(function(e) {
Use <input type="button"> instead of <input type="submit"> and add an onclick function like this:
<input type="button" onclick="_submitForm()" value="send that fancy mail">
And then your js will be:
function _submitForm(){
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
}
I hope that solved your problem.

PHP-AJAX passing input text to action url directly with ajax

Html:
<form id="yourFormId" method="POST" action="/">
{{csrf_field()}}
<div id="check" class="input-group margin-bottom-sm">
<input class="form-control" type="text" name="find" placeholder="Search">
<button type="submit"><div id="search" class="input-group-addon"><i class="fa fa-search"></i></div></button>
</div>
</form>
JS:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + this.val() );
});
});
</script>
That script doesn't work. I need an ajax solution to pass dynamically my input text to action url. How to do that?
Try this:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + $(this).val() );
});
});
</script>
i think u want to submit your form with ajax request with dynamic text field value.
you can use simple java script function on change or click event whatever you want or with ajax request
you simple use like this
window.location.href="/"+$(this).val();
return false;
This code will submit your form on keyup (as soon as you stop typing)
var timerid;
jQuery("#yourFormId").keyup(function() {
var form = this;
clearTimeout(timerid);
timerid = setTimeout(function() { form.submit(); }, 500);
});
In this code you intercept the form submit and change it with an ajax submit
$('.form-control').bind('keyup', function() {
$("#yourFormId").submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: '/url/toSubmit/to',
data: $("#yourFormId").serialize(),,
success: function (response) {
//write here any code needed for handling success }
});
});
});
To use the delay function you should use jQuery 1.4. The parameter passed to delay is in milliseconds.

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

Perform JavaScript on submit of form

I use a JavaScript to load new pages on my webpagepage. looks like this:
function loadpage(page,div) {
$.get(page, function(data) {
$(div).html(data)
});
};
So when i submit my form, I want to use that function to load the php-page you normally would set as your "action" attribute in the form-tag. So how do I get the form to POST or GET(doesen't really matter) all its content and use the function.
Now, when I write:
<form action="javascript:loadpage('bla.php','#content');" method="post">
...
</form>
it loads bla.php the way i want it to but no data is being passed byt the POST...
Is there a solution to this problem? Thank you very much in advance.
see form.onsubmit event
Using your method, you would do it as follows:
Javascript:
function loadpage(page, div, form) {
var GETdata = '';
if ( form ) GETdata = $(form).serialize();
$.get(page, GETdata, function(data) {
$(div).html(data)
});
};
HTML:
<form action="javascript:loadpage('bla.php','#content', this);" method="post">
...
</form>
A better way would be to use non-obtrusive Javascript. Remove the inline javascript:
<form id="theForm" action="" method="post">
...
</form>
and bind your event handler from within your Javascript code:
$('#theForm').submit(function(e){
e.preventDefault();
loadpage('bla.php','#content', this);
});

Categories

Resources