Pass html5 form custom attributes to JSON - javascript

This is the HTML that i created for the registration page
<form role="form" action="" method="post" id="register_form">
<input type="text" id="facebook-autocomplete" name="facebook" class="form-control mdb-autocomplete GJ-search">
<input type="text" id="beatport-autocomplete" name="beatport" class="form-control mdb-autocomplete GJ-search" required>
<input type="email" id="inputValidationEmail" name="email" class="form-control" >
<input type="password" id="inputValidationPass" name="password" class="form-control" >
<input type="checkbox" class="custom-control-input" name="termsAndConditions" id="termsAndConditions" >
<input type="checkbox" class="custom-control-input" name="gdprAccept" id="gdpr" >
<button class="btn btn-outline-info btn-rounded btn-block my-4 waves-effect z-depth-0" value="Submit" type="submit">Sign up</button>
</form>
This is the JavaScript that extracts the form to JSON and console logging it and it works.
//stringify form to JSON string
const serialize_form = form => JSON.stringify(
Array.from(new FormData(form).entries())
.reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
);
$('#register_form').on('submit', function(event) {
event.preventDefault();
const json = serialize_form(this);
console.log(json);
});
I add two new attributes to the beatport input by adding this jquery
$('.beatport #beatport-autocomplete').attr('data-beatport-id', "id pulled from api");
$('.beatport #beatport-autocomplete').attr('data-beatport-name', "name pulled from api");
The Json Result is after adding two new attributes is:
{"facebook":"big show","email":"dfghdfsghg#gmail.com","password":"fsdghfjgh","termsAndConditions":"on","gdprAccept":"on"}
You see that the two new attr are missing and when I add them the input looks like this:
<input type="text" id="beatport-autocomplete" name="beatport" class="form-control mdb-autocomplete GJ-search" required data-beatport-id="12345" data-beatport-name="artist name">
and the JSON result should be like this:
{"facebook":"big show","beatportId":"12345","beatportName":"artist name","email":"dfghdfsghg#gmail.com","password":"fsdghfjgh","termsAndConditions":"on","gdprAccept":"on"}

If you want to add data to your form you can use hidden input and set the value via js
HTML
<input type="hidden" name="beatportID">
JS
$('[name="beatportID"]').attr('value', 'my data');

If you are looking to extract data attributes from a html element and you are using jQuery already to set them i think the following might be what you are looking for. (Not exactly sure from your question what your desired result is) if possible perhaps you could explain a little further?
https://api.jquery.com/data/
Please check below for an example of that i mean.
Firstly lets say the following is your registration form.
<input type="text" id="name" />
<input type="text" id="email" />
<input type="text" id="phone" />
<input type="text" id="age" />
You would then add your two data attributes to let say the name input.
$('#name').attr('data-beatport-id', "id pulled from api");
$('#name').attr('data-beatport-name', "name pulled from api");
You can then serialize_form and add it to json variable.
let json = serialize_form(this);
And then use the following to get data attributes from the '#name' input.
json.beatport-name = $('#name').data("beatport-name")
json.beatport-id = $('#name').data("beatport-id")
You can then console log this json object.
console.log(json)

Related

Reloading div content using jquery

<div id="user_addr">
<!--- some dynamic content here, which is being loaded from db --->
<div class="add_address" >
<div class="error"></div>
<input type="hidden" id="addr_id" value="0"/>
<input type="text" id="usr_name" class="medium-input" placeholder="Enter Full Name" maxlength="50"/>
<input type="text" id="addr_line1" class="large-input" placeholder="Address Line 1" maxlength="100" />
<input type="text" id="addr_line2" class="large-input" placeholder="Address Line 2" maxlength="100"/>
<input type="text" id="city" class="small-input" placeholder="City Name" maxlength="50"/>
<input type="text" id="state" class="small-input" placeholder="State Name" maxlength="50"/>
<input type="text" id="pincode" class="small-input" placeholder="Pin Code" maxlength="6"/>
<input type="text" id="phone" class="medium-input" placeholder="Mobile Number" maxlength="10"/>
<input type="submit" value="Save" class="save_address"/>
</div>
</div>
I'm trying to reload/refresh div with id usr_addr whenever user click save button.
I'm using
$('.save_address').click(function () {
alert('hi'); <--- doesn't prompt in second call
<!--- saving data to db --->
$('#user_addr').load(location.href.replace('#', '') + ' #user_addr');// refreshing div to get latest saved data
}
But, for the first time when I click Save, it works fine, but div gets nested and in the source code, it becomes
<div id="user_addr">
<div id="user_addr"> <--- nested after function call
....
....
</div>
</div>
And, then save button doesn't work or unable to call js function. Could anyone suggest solution for this issue ?
Some things to fix this :
$(document).on('click','.save_address',function () { // 1. use event delegation to be able to listen to .save_address element, whenever it's loaded via Ajax
var url = location.href.replace('#', '') + '#user_addr';
console.log(url); // just to be sure
$.get(url, function(data){ // 2. perform an Ajax request to fetch your new content, and use a callback to handle the content
var data = $(data).find('#user_addr').html(); // 3. find the new content in the DOM
console.log(data);
$('#user_addr').html(data); // 4. insert it
});
});
Hope this will help :)
NB: I wouldn't use a input[type=submit] as long as there is no form element there, but I would use a button
Just change id="user_addr" to id="user_addr_container' and js to
$('#user_addr_container').load(location.href.replace('#', '') + ' #user_addr');

How to pass input field values as a url query string that will be opened on click of a submit button?

I would have to input fields like this
<form>
<input type="text" id="keyword" placeholder="XXX">
<input type="text" id="state" placeholder="XXX">
<button type="submit" id="submit">Submit</button>
</form>
On click of the submit I would like to send them to a new page with the value of the input appended to the url with query string.
http://www.link.com/page?keyword=XYXYX&state=XZXX
Here is my start thinking but was thinking .serialize() can handle this better than this example
var keywordVal = $("#keyword").val();
var stateVal = $("#state").val();
$( "form" ).on( "submit", function() {
event.preventDefault();
location.href='http://www.link.com/page?keyword=' + keywordVal + '&state=' + stateVal
});
let me know if i am approaching it the right way..
You don't need JavaScript to do this.
Simply add an action attribute with the URL and set the method attribute to GET (this will append the named field values as a query string).
<form action="<yourURL>" method="GET">
<input type="text" id="keyword" name="keyword" placeholder="XXX">
<input type="text" id="state" name="state" placeholder="XXX">
<button type="submit" id="submit">Submit</button>
</form>
NOTE: You'll need name attributes on your fields.
Fiddle: http://jsfiddle.net/pjh7wkj4/
No need any jQuery/javascript to do that, form tag is providing those functionality. Adding action and method (GET) attributes will give you the results what you expect.
<form action="<target_url>" method="GET">
<input type="text" id="keyword" name="keyword" placeholder="XXX">
<input type="text" id="state" name="state" placeholder="XXX">
<button type="submit" id="submit">Submit</button>
</form>

How to set passed values into template's fields?

In tornado's template in I passed from code dictionary data with keys username and code
data = {'username' : 'pal', 'code' : 16281}
in ready function I am trying to set passed values to two inputs on page
$(document).ready(function() {
var d = "{{data}}";
alert(d);
$('#code').val({{data['code']}});
$('#username').val(d['username']);
});
...
<label for="username" class="ui-hidden-accessible">Username:</label>
<input type="text" placeholder="Username" name="username" id="username" class="large_input">
<label for="code" class="ui-hidden-accessible">Code:</label>
<input type="text" placeholder="Code" name="code" id="code" class="large_input">
Alert shows that dictionary is ok, but when I try to access on any way I got undefined value. I tried with passed data and with js dictionary d but it didn't work.
How to set passed values into template's fields ?
For HTML this would work:
<input value="{{data["username"]}}" type="text" placeholder="Username" name="username" id="username" class="large_input">
For your JS I image you need to write this instead:
$('#code').val('{{data['code']}}');

Submitting 2D array form input using AJAX in Javascript

I have a form as follows:
<form name="chat" id="chat" action="" onsubmit="sendMessage()">
<a name="chat"> </a>
<input type="text" name="chat" id="chat" size="38" maxlength="50" vertical-align="middle">
<input type="hidden" name="action" id="action" value="checkresponse">
<input type="hidden" name="response_Array[sessionid]" id="response_Array[sessionid]" value="keu88lh88ini89dgnccob54f27"><br>
<input type="text" name="response_Array[top]" id="response_Array[top]" value="a">
<input type="text" name="response_Array[second]" id="response_Array[second]" value="b"><br>
<input type="text" name="response_Array[third]" id="response_Array[third]" value="c"><br>
<input type="text" name="response_Array[fourth]" id="response_Array[fourth]" value="d"><br>
<input type="text" name="response_Array[input][0]" id="response_Array[input][0]" value="input 0"><br>
<input type="text" name="response_Array[that][0]" id="response_Array[that][0]" value="that 0"><br>
<input type="submit" name="submit" id ="submit" value="SEND" style="width: 45px">
</form>
When the user clicks Submit, I need to send all the input fields to the server.
But, the page should not get refreshed. So, I have created sendMessage(),in which I have used XMLHttpRequest object to send the form submit request.
To read input fields, I have used in sendMessage():
var infoStr = "chat="+document.forms[0]['chat'].value;
infoStr += "&action="+document.forms[0]['action'].value;
I want to know how should I read the 2D array :response_Array and parse it into a JSON string so that it can be passed to the php server code.
It is so simple
var infoStr=""
for(var i=0;i<document.forms[0].elements.length;i++)
{
infoStr+=document.forms[0].elements[i].name+"="+document.forms[0].elements[i].value+"&";
}
alert(infoStr); // You will have the full name value pairs.
Hope this solves your problem.

jQuery serialize function with multple forms

I'm using the jQuery .serialize function and can't get it to serialize the proper form on submit.
my js code:
function getquerystring(form) {
return $("form").serialize();
}
my forms:
<div class="leave_message_box">
<form name="leave_message_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="leave_message" />
<input value="Leave Message" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "leave_message_form")'></p>
</form>
</div>
<div class="outside_job_box">
<form name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
I must be doing something wrong in passing the variable. the full code # pastie. The function I have does work, however, its always the last form that gets submitted.
Using this code:
$("form")
will find all the <form> elements in your document.
Given that form is a string containing the name of the form, what you want instead is this:
$("form[name='" + form + "']")
Looking at your supplied code, I have this suggestion. Instead of passing the form name to your function, why not just pass the form itself?
<button onclick="xmlhttpPost('blah', this.form)">
You also don't need to put javascript: in the onclick, onfocus, onwhatever properties.
I would suggest putting an ID attribute on the form and then using that ID as an explicit selector for jQuery:
<div class="outside_job_box">
<form id="outside_job_form" name="outside_job_form">
<input type="text" name="clock_code" placeholder="Clock Code" />
<input type="text" name="message" placeholder="Message (Blank for none)"/>
<input type="hidden" name="type" value="ouside_job" />
<input value="Outside Job" type="button" onclick='JavaScript:xmlhttpPost("clockin.php", "outside_job_form")'></p>
</form>
</div>
Then you would select and serialize it like this;
var f = $("#outside_job_form").serialize();
Not only making your code more effecient but more readable, in my opinion.
If the sole purpose is to encode simple text into URL format then use encodeURIComponent().

Categories

Resources