How to serialize a form that contains jQuery ajax loaded fields? - javascript

This is the main form:
<div>
<form method="post" class="register" id="wiz-config">
<!-- HTML -->
<input type="radio" value="187" name="group-1" id="product-187" class="aselector" >
<input type="radio" value="188" name="group-1" id="product-188" class="aselector" >
<!-- HTML -->
<!-- Other ajax fields -->
</form>
</div>
Other ajax fields are loaded via ajax.
The problem is that if I use
jQuery( document ).ready(function() {
var str = jQuery( "#wiz-config" ).serialize();
console.log(str);
});
it returns is "empty". Why?

You've just forgotten to put the selector # :
$( "#wiz-config" ).serialize();

Your jQuery selection is wrong. You need # because you are trying to select by the Id.
$("#wiz-config" ).serialize();
ID Selector (“#id”) : Selects a single element with the given id
attribute.
Or if you have only one form in your page, you may try this as well to get the form
var _form = $("form");
console.log(_form);
var serializedVersion = _form.serialize();
EDIT : As per the comment, you are not getting the dynamically added form elements. The only reason i can think of is, You might not be giving the name attribute and it's value to these dynamically added form elements. serialize method will serialize only those elements with a valid name attribute.
The below should work without any problems.
$(function(){
var newItems="<input name='place' type='text' />";
$("#wiz-config").append(newItems);
});
Here is a working sample.

You are calling an element not an ID.
$("wiz-config").serialize();
Is looking for an element, such as p, div, etc.
To call an item by ID, you need to add a leading #:
$("#wiz-config").serialize();

Related

Select the custom tag from button attribute

I have created a button element structure like below
<input
type="button"
class="btn btn-primary"
name="redirect"
value="<mycustomtag data-id=15>"
title="<mycustomtag data-id=14>"
>
Now, whenever the DOM gets ready I'm trying to find out the custom element and trying to replace with string. But I'm not able to replace the custom element.
The snippets I have used to find is as below
jQuery("mycustomtag").each(function(){
//process here
});
PS this works fine in the following case:
<div><mycustomtag data-id=20></div>
<h4><mycustomtag data-id=18></h4>
your code
jQuery("mycustomtag")
will try to find tag named mycustomtag, and what i understand is you are trying to replace the input attributes right ?
try following
//if you want to get values
var value = $("#btnCustom").attr("value");
var title = $("#btnCustom").attr("title");
alert(value);
alert(title);
//if you want to set values
$("#btnCustom").attr("value","replacevalue");
$("#btnCustom").attr("title","replace value 2");
value = $("#btnCustom").attr("value");
title = $("#btnCustom").attr("title");
alert(value);
alert(title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input
type="button"
class="btn btn-primary"
name="redirect"
value="<mycustomtag data-id=15>"
title="<mycustomtag data-id=14>"
id="btnCustom"
>
You couldn't find them since the value of an attribute is considered just like a string.
To find those elements you need to select them based on the main tag by selecting the specific attribute using .prop(), like :
$('input').each(function() {
$(this).val();
$(this).prop('title');
});
PS this works fine in the following case
That because in this case it's considered as a tag element in your DOM that why jQuery can find it by a simple selector.
$('input').each(function() {
console.log($(this).val());
console.log($(this).prop('title'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn btn-primary" name="redirect" value="<mycustomtag data-id=15>" title="<mycustomtag data-id=14>">
In your first HTML code what you're looking for is in the value or title attribute. In your second it's the element name.
To select an element based on its value, use the following syntax:
$("input[value='<mycustomtag data-id=15>'")
To select an element based on its title works similarly.
If you put your custom tag in an attribute of another tag it won't be rendered in the page, in other words it won't be part of the document DOM tree, it will be just a string in an attribute, that's why when you use jQuery("mycustomtag") you don't get anything, but it will work if you put it as a child of a div or a span.
So in your specific case you will need to use .attr() method to get it from this specific attribute or .val() method if it's in the value.
jQuery("input").attr("title");
jQuery("input").val();
Demo:
console.log(jQuery("input").attr("title"));
console.log(jQuery("input").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input
type="button"
class="btn btn-primary"
name="redirect"
value="<mycustomtag data-id=15>"
title="<mycustomtag data-id=14>"
>

Get tags value in "tag box" created in jQuery

I came across this post on SO, and I basically copied the code (html, css and jquery) to my web page. Everything works except that I don't know how to get the tags when my html form is submitted.
From my understanding of the javascript code, the tags are stored in tags, they are not stored in fields, so my question is how to capture those tags when the form where it's embedded is submitted?
Thanks
You can iterate a jquery object and get the child's content in this way:
var tags = '';
$('#tags > span').each(function() {
tags = tags + $(this).html() + ',';
});
$('#inputInForm').val(tags);
Just add a hidden input field to each of your tags like this when you create them:
<span class="tag">
tag-name
<input type="hidden" name="tags[]" value="tag-name">
</span>
This way you will automatically get the tags array when you post the form (obviously those tags should be within your form).

show submit <a href> link onchange and pass the value of the input box changed

I am not a JavaScript person really, I write in ASP and use a SQL database in the backend. But our marketing director requested a change that will use JavaScript.
On our view cart page, we're currently displaying an input box with a modify button to allow customers to change the quantity of the listed item (in that row... there could be multiple products in their cart, each having their own quantity input).
<form method="post" action="updateitem.asp">
<input type="hidden" name="product_id" value="<%= PRODUCT_ID %>">
Quantity: <input type"text" name="quantity">
<input type="image" name="Submit" src="/graphics/modify.gif" align="middle" border="0" alt="Continue">
</form>
What I'd like to make work is something like this. Hrm, assuming I need to do my form/div name differently for each product? I can easily write the product_id into the id tags but then assuming I'd also need to loop through my function for each one. I've gotten this far in writing the replacement code:
Get Dataset from Database (items in cart) and loop through:
<form method="post" action="updateitem.asp" id="updateitems<%= PRODUCT_ID %>">
Quantity: <input type="text" name="qty<%= PRODUCT_ID %>" OnChange="Javascript:UpdateQty()")
<div id="showlink<%= PRODUCT_ID %>">
<br /><span class="BodyTiny">update</span>
</div>
</form>
END LOOP
So if the quantity changes, it displays the word "update" where they can click and it passes whatever quantity that is in the quantity field to the updateitem.asp (in a way I can then update it in the database in ASP/SQL). In the code above, if we could just insert the new # in the a href statement after quantity=, then I could fix it in the updateitems.asp page without a problem.
I'm not sure where to even begin honestly, I have this so far:
LOOP through dataset so each product has its own function
<script Language="JavaScript">
<!--
function UpdateQty(updateitems<%= PRODUCT_ID %>) {
Show div updateitems<%= PRODUCT_ID %>
Replace NEWQUANT within that div with the value in the input field qty<%= PRODUCT_ID %>
}
//-->
</script>
END LOOP
I'm having a few problems...
I am not sure how to write the function UpdateQty. It should A) display the stuff in div id=showlink, and B) add the # from the input named quantity quantity to the href so I can update it in the database on the next page
If they have JavaScript turned off, they should be able to enter a new quantity and just hit enter for it to submit the form. I believe this will work as its a form with 1 text input and 1 hidden one, so just hitting enter in the text input should submit it. But that should still work with whatever JavaScript is added to make the showlink div show if it changes.
Do I need to add a class to my CSS for showlink? If so, what do I need to put in it?
Any help would be greatly appreciated!
Mahalo!
so what you can do for updateQty is have one function that will be correct for all products in a list just by making a function that finds all the necessary elements by relative paths.
//in this function the context is the element, so the
//`this` variable can be used rather than a param
//for the product id
function updateQty() {
//show the update link
var parent = this.parentNode;
//assumes only the update text uses the class bodyTiny, and that there
//is only one element using it. obviously making this invariant true
//would be trivial by adding a different class name
var updateText = parent.getElementsByClassName("bodyTiny")[0];
updateText.style.display = 'block';
var updateLink = updateText.parentNode
, updateHref = updateLink.href;
//next we find the current quantity and replace it with the input
updateHref = updateHref.replace(/qty=(\d*)/, 'qty='+this.value);
//then we set the link element's attribute
updateLink.href = updateHref;
//now when you mouse over the link you should see the url has changed
}
You can also set your form to POST the equivalent data, and then I guess on the server side you will have your OnGetPage and OnPostback both delegate to the same method with the parameters either parsed out of the query string or out of the post data.
You can see it running on jsfiddle. Hopefully this helps!

Jquery appending value of html to input box but not text within a span

I have an ajax query that brings back a searched name and id:
if($result)
{
while($row=mysqli_fetch_array($result))
{
extract($row);
echo "<li>".$row['first_name']." ".$row['last_name']."<span class='uid'>".$row['user_id']."</span></li>";
}
}
What I am trying to do is append the first and last names to a search box and then retrieve the userid and place that in another search box.
$('li').click(function(){
$('.client_name').not('span.uid').val($(this).text());
$('.listbox').hide();
});
The above jquery does not work as I feel I am using the 'not' property wrongly. Is it possible to split these values ?
html is as follows
<div class="form_align">
<label>
Client Name
</label>
<input type="text" class="client_name" />
<label>
Client Account No.
<span class="small">This is important !</span>
</label>
<input type="text" class="client_account_no" />
<div class="listbox">
<div class="nameslist">
</div>
</div>
</div>
I recommend changing the AJAX response to surround the names in their own <span class='ajaxname'>. That will make it a lot simpler to target the name separately from the sibling node <span class='uid'>. Otherwise, to exclude the value of the <span class='uid'> you would need to do something tricky like temporarily remove it from the DOM to get the <li>'s text then place it back in. All way too complicated.
echo "<li><span class='ajaxname'>".$row['first_name']." ".$row['last_name']."</span><span class='uid'>".$row['user_id']."</span></li>";
Since the AJAX response sends a new <li> into your DOM, you will need to use .on() to bind the click event.
$('li').on('click', function(){
// Get the name from its <span> and put it into the input
$('.client_name').val($(this).find('.ajaxname').text());
// Get the uid and put it inot .client_account_no
$('.client_account_name').val($(this).find('.uid').text());
$('.listbox').hide();
});
And what do you know, it works (jsfiddle).
Addendum:
Other answer never materialized, so here is an arguably better solution using a data-uid attribute in the AJAX-returned HTML
// PHP supplies the user_id in an HTML attribute data-uid
echo "<li data-uid='" . $row['user_id'] . "'>".$row['first_name']." ".$row['last_name'] . "</li>";
The JavaScript has a much easier job then:
$('li').on('click', function(){
// Get the name, which is just the <li>'s text content...
$('.client_name').val($(this).text());
// Get the uid from the data-uid attribute
$('.client_account_name').val($(this).attr('data-uid'));
$('.listbox').hide();
});

How can I create a dynamic form using jQuery

How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.

Categories

Resources