<form method="POST" action="" id ="formaclient" >
<input name="fullname">
<input name="fullname1">
<input name="fullname2">
<input name="fullname3">
<input class="btn-update">
</form>
$(".btn-update").click(function (ev) {
ev.preventDefault();
var data = $(this).find("#formaclient").serialize();
console.log(data);
$.ajax({
type: 'POST',
url: 'demo/client_view_search_content.php',
data: $("#formaclient").serialize(),
success: function () {
alert('Success!')
},
error: function () {
alert('Failure!')
}
});
return false;
});
Something is wrong with
var data = $(this).find("#formaclient").serialize();
I'm not getting data, how to change var data = $(this).find("#formaclient").serialize(); that I will get data from form ?
Use closest() instead of find(). find() will check for the children only. While closest() will check for the parents
var data = $(this).closest("#formaclient").serialize();
Since the id is unique, you can directly get the form like this,
var data = $("#formaclient").serialize();
If you have multiple forms, use like this
var data = $(this).closest("form").serialize();
I think you are using .find() wrong, because .find() searches for element descendants(children).
I think you should use $("form#formaclient").serialize() in order to serialize data.
You are using this which is pointed to the .btn-update object. using .find() will check for the children of object only. use below to serialize the data :
var data = $("#formaclient").serialize();
.find() descends from the current element. Obviously, since there are no elements within the button, you won't be able to find the form.
Since you have the id of the form, why don't you just use it to locate the form?
$('#formaclient').serialize(); will do the trick.
Also, remember that all IDs must be unique, so you should not worry about mixing up the forms.
You don't need to find elements with specific id values - a simple $('#formaclient') will do fine. It will also avoid the need to serialize the form data twice as your code attempts to do at present.
Your end result should look like this:
$(".btn-update").click(function(ev) {
ev.preventDefault();
var myData = $('#formaclient').serialize();
console.log(myData);
$.ajax({
type: 'POST',
url: 'demo/client_view_search_content.php',
data: myData,
success: function () {
alert('Success!')
},
error: function () {
alert('Failure!')
}
});
return false;
});
As others have pointed out, trying to find an element will only search descendant elements from the one you start from (the button in your case).
Related
I have some input in my form,now I want to get the json object from the form without some input named point,What's wrong with my code?I have to remove them.It seems not work for not() function.How to fix my code?
<form id="myform">
<input name='student' value='a'/>
<input name='student' value='b'/> '
...
<input name='point' value='90'/>
<input name='point' value='95'/>
</form>
Now I only want to submit the student data to the server.So I write the code:
var data = $('#myform').not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
but the result still have point data.What's wrong with not() function?
breaking down your code $('#myform') selects your form, in this case, only one object, then you filter that object with .not("input[name='point']") but there is only one object which is the form itself.
You want to filter the form's children instead, so just add .children() like this:
var data = $('#myform').children().not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
Hope this will help you.
$('#myform input[name!=point]').serializeArray()
Your selector is faulty.
$('#myform').not("input[name='point']").serializeArray()
...says, "Serialise the form with ID 'myForm' which is not also an input and has the name 'point'.
Rather, you mean: "Serialise the form with ID 'myForm' but omit its child inputs with name 'point'.
Here's a non-jQuery way, using native FormData.
//get the form as form data
var fd = new FormData(document.querySelector('#myform'));
//delete any elements pertaining to [name=point]
fd.delete('point');
//et voila; this shows we retain only the student fields
for (var key of fd.keys()) alert(key);
What i have is a div with text inputs. What i want to do is send the div's HTML code to the server to be used on another page like so:
$.ajax({
url: 'process.php',
type: 'POST',
data: {
html: $("#form").html()
},
success: function (data) {
}
});
The thing is, if a user types in some data into the text inputs, that data is lost since its not part of the HTML. Is there a way i can force this data into the HTML? eg by using javascript to edit each input's value attribute?
Thanks in advance
Try the input event:
$(document).on('input', 'input.your_input', function() {
var that = $(this);
that.attr('value', that.val());
});
Inspect the input element and try type something:
$(document).on('input', '#textInp', function() {
var that = $(this);
that.attr('value', that.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="textInp" />
You can try sending the input values via parameters in the ajax function.
Try to run this snippet before making the call,
$("#form :text").attr("value",funcion(){
return $(this).val();
});
Instead of binding change event to all the input elements initially you can add the attribute before sending them to server.
You can try like this:
$("input").on('change', function() {
$(this).attr('value', $(this).val());
});
I'm getting the values of checkboxes when a user submits the form and storing their values as an array, so the form looks like this:
<!-- gym_create.html - I have removed the other inputs in the form for brevity -->
<form class="create-gym" role="form">
<input type="checkbox" name="gymTags" value="Bodybuilding" id="tagBodybuilding" class="tag-checkbox"/>
<input type="checkbox" name="gymTags" value="Powerlifting" id="tagPowerlifting" class="tag-checkbox"/>
<button type="submit" class="btn create-form-submit">Save gym</button>
</form>
And then I collect that information in my JS file associated with the form:
// gym_create.js - I have removed the other values I collect apart from the gymName value for brevity
Template.gymCreate.events({
"submit .create-gym": function (e) {
e.preventDefault();
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]:checked').map(function() {
return $(this).val();
}).get()
});
// Collect values from form when submitted
var gymDetails = {
gymName: $(e.target).find('[name=gymName]').val(),
gymTags: tagOutput,
}
// Call method here
}
});
I can then output these in my template using {{gymDetails.gymTags}} but this produces the following in the browser:
"{"TAGOUTPUT":["BODYBUILDING","POWERLIFTING"]}"
What I want is a way to store the values as JSON so they are like so:
{"gymTags": {
"bodybuilding": "true",
"powerlifting": "false"
}}
So that I can output each tag on it's own and also access only tags which are 'true' (that were checked) later on.
Does anyone know how I go about this? I wrangled with it all yesterday and the best I could come up with was the =JSON.stringify
I don't want to pass the entire form to JSON, just the checkboxes, is JSON.stringify what I want to be doing or am I barking up the wrong tree.
I think this should do it. You were just returning the just the value of the inputs. You want to return a json object, where the value is the "index" and the checked property is the "value" of the object.
var tagOutput = JSON.stringify({
tagOutput: $(':checkbox[name=gymTags]').map(function() {
var op = {};
op[this.value] = this.checked;
return op;
}).get()
});
Edit: as noted by Da Rod, to use both checked and unchecked checkboxes, you must remove the ":checked" selector.
Since your selector is only grabbing items that are checked, they are all "true". That being the case, you need to change the way you are using "map" to add properties to tagOutput.
var tagOutput = {}
$(':checkbox[name=gymTags]').map(function() {
tagOutput[this.value] = this.checked;
})
});
I am trying to make a javascript function that modifies the hidden value of a form depending on what button you click and then send it via post to a page that processes it.
I checked that the value is modified correctly, but when the post is sent the default value is sent.
Any help?
Here the js function:
function citar(key)
{
document.getElementById('esta-cita').value=key;
document.getElementById('form-cita').submit();
}
EDIT: I did this and now it works. jQuery!
function citar(key)
{
$("#ncita").attr("value", key);
$('#form-cita').submit();
}
Your main problem here is that you are using
document.getElementsByName
which returns an array. Therefor the implementation of key is invalid.
if you are using jQuery you might use
$('[name=esta-cita]').each(function() {
$(this).val(key); //this will insert key to all esta-cita named parameters, even if only 1
});
if you only have 1 parameter of this kind so :
$('[name=esta-cita]').val(key);
});
i deeply recommand you to use jQuery jQuery website
in javascript's case i would have recommand you to use
document.getElementById on 'esta-cita' as well.
if you want to insert key to all elements in javascript i would recommand a very efficient way :
document.getElementsByName('esta-cita').forEach(function(entry) {
entry.value = key; //entry indicates a cell in the array
This returns an array of elements, so you'll have to iterate through it like a normal array.
function citar(key)
{
document.getElementsByName('esta-cita').value=key;
document.getElementById('form-cita').submit();
}
Should be:
function citar(key)
{
var derp = document.getElementsByName('esta-cita');
for (var i=0;i<derp.length;i++) {
derp[i].value = key;
}
document.getElementById('form-cita').submit();
}
Or just document.getElementsByName('esta-cita')[0].value=key; if you just want the first one
Try with,
document.getElementsByName('esta-cita')[0].value=key;
you can access to a length property document.getElementsByName('esta-cita').length to know how many elements are matched
Alternatively you can try this
function citar(key)
{
document.forms['form-cita'].esta-cita.value = key;
document.forms['form-cita'].submit();
}
HTML should be like
<form action="putActionHere" method="POST" enctype="multipart/form-data" id="form-cita">
<input type="hidden" name="esta-cita" id="esta-cita" value="yourval">
...
<input type="submit" value="Submit" onClick="citar('keystring');" />
</form>
If I have a input textbox like this:
<input type="text" id="searchField" name="searchField" />
How can I set the value of the textfield using javascript or jQuery?
You would think this was simple but I've tried the following:
Using defaultvalue
var a = document.getElementById("searchField");
a.value = a.defaultValue;
Using jQuery
jQuery("#searchField").focus( function()
{
$(this).val("");
} );
Using js
document.getElementById("searchField").value = "";
None of them are doing it... :/
In Javascript :
document.getElementById('searchField').value = '';
In jQuery :
$('#searchField').val('');
That should do it
With jQuery, I've found that sometimes using val to clear the value of a textbox has no effect, in those situations I've found that using attr does the job
$('#searchField').attr("value", "");
Use it like this:
$("#searchField").focus(function() {
$(this).val("");
});
It has to work. Otherwise it probably never gets focused.
To set value
$('#searchField').val('your_value');
to retrieve value
$('#searchField').val();
I know this is an old post, but this may help clarify:
$('#searchField')
.val('')// [property value] e.g. what is visible / will be submitted
.attr('value', '');// [attribute value] e.g. <input value="preset" ...
Changing [attribute value] has no effect if there is a [property value].
(user || js altered input)
Try using this:
$('#searchField').val('');
First, select the element. You can usually use the ID like this:
$("#searchField"); // select element by using "#someid"
Then, to set the value, use .val("something") as in:
$("#searchField").val("something"); // set the value
Note that you should only run this code when the element is available. The usual way to do this is:
$(document).ready(function() { // execute when everything is loaded
$("#searchField").val("something"); // set the value
});
This worked for me:
$("#searchField").focus(function()
{
this.value = '';
});
this is might be a possible solution
void 0 != document.getElementById("ad") && (document.getElementById("ad").onclick =function(){
var a = $("#client_id").val();
var b = $("#contact").val();
var c = $("#message").val();
var Qdata = { client_id: a, contact:b, message:c }
var respo='';
$("#message").html('');
return $.ajax({
url: applicationPath ,
type: "POST",
data: Qdata,
success: function(e) {
$("#mcg").html("msg send successfully");
}
})
});