Sending one of multiple forms with jQuery - javascript

I'm doing a thing like the follow-:
$.each(data2, function(key2, val2) {
$('#posts').append('<div class="send_comment" align="right">');
$('#posts').append('<input type="hidden" class="com_post_id" value="'+i+'"><br /\>');
$('#posts').append('Author: <input type="text" class="com_author"><br /\>');
$('#posts').append('Img: <input type="text" class="com_img"><br /\>');
$('#posts').append('Text: <input type="text" class="com_text"><br /\>');
$('#posts').append('<button class="new_comment">Send</button>');
$('#posts').append('</div>');
});
How can I send these fields with $.post? With $(this), I can get the clicked element, but then?

Since it is dynamically injected element,you should bind the functionality using jQuery on
$(function(){
$(".send_comment").on("click",".new_comment",function(e){
e.preventDefault();
var item=$(this);
var postId=item.parent().find(".com_post_id");
var author=item.parent().find(".com_author");
var msg=item.parent().find(".com_text");
$.post("yourPage.php", { id : postId, author:author ,msg:msg },function(result){
//do whatever with result
alert(result);
});
});
});
http://api.jquery.com/on/
jQuery on will work on current and future elements.

data = $(this).closest('form').serialize()

I always found the modal form example from jqueryui's site as a good example of how to send data from a form: http://jqueryui.com/demos/dialog/#modal-form
Essentially give your fields ids, then:
var author = $( "#author" ),
image = $( "#image" ),
text = $( "#text" ),
allFields = $( [] ).add( author ).add( image ).add( text );
Then use post:
$.post("your_url_that_processes_data",allFields, function(data){
// do something with data
});
If you have multiple forms that vary slightly there are plenty of ways to go about that. I'd recommend either changing the action URL OR grabbing an "id" from some DOM element some how. Maybe you can change the form id to something like : "form-".id in your script then read it before you submit.
I can potentially try to help with a more detailed use case?

Related

Get files from form without querying for input field

I'm trying to upload files using AJAX. However, I'm having issues grabbing the files from my form. I want to gather all the
<input type="file">
fields that are nested within the form, without using their specific ids. So, not like this:
console.log($( "#i_dont_want_to_query_for_this_id" )[0].files);
//FileList {0: File, length: 1}
I feel there must a be way to get them from the form element itself:
<form class="part-form">
...
<input type="file" id="i_dont_want_to_query_for_this_id">
</form>
This is how I handle the submit:
$( ".part-form" ).each(function () {
var $me = $( this );
$me.on('submit', function (event) {
event.preventDefault();
var formElement = $me[0];
var fd = new FormData(formElement);
...
}
I guess this can also be achieved using classes and each() on these, but I feel there must be a way to grab all files in a submitted form by simply using the data in the form itself, I just cannot find it.
Any help is greatly appreciated!
You can use an attribute selector like $("file[type=input]") to get all the file inputs. Here's a fiddle.
$(document).ready(function() {
$( ".part-form" ).each(function () {
var $me = $( this );
$me.on('submit', function (event) {
event.preventDefault();
var $resultDiv = $("#result-div");
$me.find("input[type=file]").each(function(index, fileInput) {
for(var i = 0; i < fileInput.files.length; i++) {
// Do whatever you really want to do with the file.
var $span = $("<span />");
$span.text(fileInput.files[i].name);
$resultDiv.append($span);
}
})
});
});
})
Use can use selector $("input[type='file']")
$(document).on('change', 'input[type="file"]', function(){
console.log($(this)[0].files)
alert($(this)[0].files)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="part-form">
...
<input type="file" id="i_dont_want_to_query_for_this_id">
<input type="file" id="i_dont_want_to_query_for_this_id2">
</form>

autocomplete on input field created with jquery after()

I have a field on which an autocomplete function is implemented. This is my code :
<%= f.text_field :auteur_1, size: 100, class:"champs_auteur", data: {autocomplete_source: auteurs_enum_path} %>
That creates the following html :
<input size="100" class="champs_auteur ui-autocomplete-input" data-autocomplete-source="/auteurs/enum" name="biblio[auteur_1]" id="biblio_auteur_1" autocomplete="off" type="text">
And this is in my javascript :
$(document).on('ready', function() {
return $('.champs_auteur').autocomplete({
source: $('.champs_auteur').data('autocomplete-source')
});
});
All that works fine. I am creating input fields using jquery after() and append(), like this :
$(document).on('ready', function () {
i = 2 ;
$(".extra_auteur").click(function(){
$('.premier_auteur').after('<div class="grid mbm"><div class="one-sixth"><label for="biblio_auteur">Auteur</label></div><input size="100" class="champs_auteur" data-autocomplete-source="/auteurs/enum" type="text" name="biblio[auteur_' + i++ + ']" id="biblio_auteur_1" /></div>');
});
});
This is minified code (mainly html) for :
<div class="grid mbm">
<div class="one-sixth">
<label for="biblio_auteur">Auteur</label>
</div>
<input size="100" class="champs_auteur" data-autocomplete-source="/auteurs/enum" type="text" name="biblio[auteur_' + i++ + ']" id="biblio_auteur_1" />
</div>
This does create the input field with an id="biblio_auteur_2" (and 3, 4 etc...).
The autocomplete doesn't work on the additional input fields. I don't see why not.
This is because you're using the element #ID instead of the class-name as in:
$( "#aut_extra" )
And #ID is always unique, and will therefore only work for 1 item. What yu need to do is have the jQuery select the CSS element class instead and not ID.
$( ".aut_extra" )
or whatever the class name is.
But you must be sure that the element which currently have the ID of aut_extra instead have a CSS class with the same name.
<div class="aut_extra"....
Crashtor is correct, page ids MUST be unique for proper functioning. However, you might have another issue. You're calling autocomplete during document ready, but when you change the dom by adding new fields, those existed after the autocomplete function was initialized.
Try calling autocomplete on each after append.
$('.extra_amatur:last').find('input[type=text]:last').autocomplete({
source: $(this).data('autocomplete-source')
});
Thanks both for your help. Both errors needed to be corrected, the first on that only classes should be used and the second that the autocomplete should be used on another event then document ready. I took on click.
This is the code (if this could ever help someone) :
$(document).on('click', '.champs_2_auteur', function() {
return $('.champs_2_auteur').autocomplete({
source: $('.champs_2_auteur').data('autocomplete-source')
});
});

reading hidden custom attribute using jquery

I have custom attribute tag in my html without id as the number can vary for them
<input type="hidden" cus_control="offer_1" value="123456">
<input type="hidden" cus_control="offer_2" value="1UYREST">
Now I want to read the value of offer_1 and offer_2 which is 123456 and 1UYREST respectively using jquery or javascript.
How will I achieve this as I don't have id for them?
You can target the attribute it self
var value = $('input["cus-control=offer_1"]').val();
Note that you should be using data-attributes, and not invalid custom attributes
Try the hidden selector
https://api.jquery.com/hidden-selector/
var hiddenElements = $( "body" ).find( ":hidden" )
I finally found a way.
var hiddenElements = $( "body" ).find( "input:hidden" ).not( "script" );
hiddenElements.each(function(){
if($(this).attr('sfc_control'))
{
var control_value = $(this).val();
var control_name = $(this).attr('cus_control');
}
});
Thanks for the suggestions

jQuery get form which button is clicked?

<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).

How to get input text value using Jquery

I have the following code, in mydata.jsp value of q is empty. What is the correct way to pass value of inputId to mydata.jsp?
<input type="text" size="25" name="inputId" id="inputId" />
and Jquery script as
<script type="text/javascript">
$(function() {
$("#inputId").autocomplete({
source: "mydata.jsp?q="+$( "#inputId" ).val(),
select:function(event,ui) {
$("#hid").val(ui.item.email)
}
});
});
</script>
When you pass $( "#inputId" ).val() as an argument to .autocomplete(), you're getting the initial value from that field before anything has been typed. That would explain why it is empty.
If you use the string version of autocomplete, it can automatically add the typed value to the URL. See the doc for the string version of source here.
If you want the URL for the source to be a dynamically generated URL, then you can also pass a function as the source and the code in that function can generate the URL/alternatives. See the doc for the source option here.
$('#inputId').keyup(function()
{
var str=$(this).val();
if(str!='')
{
$.ajax({
type:"GET",
url:"mydata.jsp",
data:"str="+str,
success: function(data){
alert(data);
}
});
}
});
Try like this. hope it will give you some solution.

Categories