mootools toQueryString of a Form - javascript

im trieing to serialize a complete form. i found the easiest way:
var tmp = $('myForm').toQueryString().parseQueryString();
var req = JSON.decode( tmp );
but it wont work.
i testet only
var tmp = $('myForm').toQueryString()
alert("data " + tmp);
also wont work. it only prints "data " nothing more..
my form is simple:
<form action="test.php" id="myForm">
<input type="text" name="user">
<input type="text" name="user_name">
<input type="submit" name="user_name_button">
</form>
the javascript code is like:
$('myForm').addEvent( 'submit', function( e )
{
e.stop();
var tmp = $('myForm').toQueryString()
alert("data " + tmp);
})
does anybody has an idea why this didn work ?

Found the error. The submit and one text field had the same name.
See the fixed version here, http://jsfiddle.net/HXsBk/1/

Related

Without using a form, how can I check an input field is not empty before running function?

I have the following code in a SharePoint aspx page ( I got an error that said I cannot use form controls... that is why the form tags are not there):
<div id="formBox">
Here is a link : <a href="" id=lnk>nothing here yet</a> <br>
<input type='text' id='userInput' />
<input name="codename" type="radio" value="codeA" /> <label for="x">X</label> <input name="codename" type="radio" value="codeB" /><label for="y">Y</label>
<input type='button' onclick='javascript:changeText2()' value='Change Text'/>
</div>
Here is the function which is supposed to concatenate the information: It works... kind of.. parts of it.
It will add the selected button to the url, and also the input text. However, it is firing before the input is filled out, and then works once you type in the box again.
I tired to add in if statement, to stop the code if the box was not filled out but it didn't work. Here is what I have...
function changeText2(){
var userInput = document.getElementById('userInput').value;
$('#formBox input[type="text"]').on('change', function() {
var linktest = 'site/info.aspx?' + $('input[name="codename"]:checked', '#formBox').val() + '=' + userInput;
alert(linktest);
});
var lnk = document.getElementById('lnk');
lnk.href = "http://www.google.com?q=" + userInput;
lnk.innerHTML = lnk.href;
}
I tried to check the input box like this, but it didn't work:
if( $('#formBox input[type="text"]').val== "") {
alert('no info');
}
It should be val() in jquery, not val. However, it will be value in javascript, not val. Simply just use unique id, try something like this,
For Jquery:
if( $('#userInput').val() === "") {
alert('no info');
}
For javascript:
if(document.getElementById("userInput").value === "") {
alert('no info');
}

understanding click(),change() and inputs scopes

I am trying to understand scope as far as inputs and clicks or checks are concerned. I am working on a project and what I am trying to do is. Ask if they work out a lot, they will answer yes or no. then I will ask them 3 question either way. I will ask how much they can bench, how much they can squat, how much they can curl. I have this part set up I will give them feedback based on what they input. What I am trying to do is add a check box to it for them to select if they are male or female. I think I should do it something like this
function one() {
a = 100;
b = 200;
c = 300;
return two();
function two() {
a += a;
b += b;
c += c;
return three();
function three() {
a += 1;
b += 1;
c += 1;
return four();
function four() {
console.log(a, b, c);
}
}
}
}
one()
I guess my question is how would I do this with click and checks and inputs. It seems no matter where I add the check box to what I have, it will not work for some reason. Either there will be a issue with the first question... Do you work out a lot? a the question will not be there. Or I will get a post era. I have a fiddle below. If someone would tell me how to make it work...or even better show me it working, I will be very thankful. I think this would help a lot of people out. I have seen a lot of good answers to this question on here, but no working examples. I think the most helpful thing for some people, is a working example they can see, I know it is for me.
ps in my fiddle i am recycling the same inputs for the questions i'm asking. Whether they work out or not, i would like to do it properly, but not my main issue.
http://jsfiddle.net/vicky1212/G24aQ/10/
I have added some explanation with the code..
$('.myOptions').change(function () {
// Remove the active class
$('.list').removeClass('active');
// Add the active class
// this.value holds the current value that is selected
// No need to use filter
$('.' + this.value).addClass('active');
});
$('#butt').click(function () {
// Better to have Lesser variables ,
var active = $('.list.active'),
$boxOne = active.find('.box1'),
$boxTwo = active.find('.box2'),
$boxThree = active.find('.box3'),
$output = $('#output'),
total = (parseInt($boxOne.val(), 10) + parseInt($boxTwo.val(), 10) + parseInt($boxThree.val(), 10)),
msg = '';
$output.addClass('error');
var dropdownValue = $('.myOptions').val(),
// you need to select the inputs specifically
// you were trying to access it using $('input') that gives the list of all the inputs
// on your page.. So you need to be more specific
$genderRadio = $('input[name=gender]');
// If dropdown is empty show some message
if (dropdownValue === '') {
msg = 'Please select an option....';
} else if (isNaN(total)) {
msg = 'Input three numbers, please...';
} // If gender is not selected show a specific message
else if ($genderRadio.filter(':checked').length === 0) {
msg = 'Please select your gender....';
} else {
// If it comes to this statemenet it means there is no error
// remove the error class
$output.removeClass('error');
if (total < 14) {
msg = "That's bad, should be higher...";
} else if (total > 15) {
msg = "That's bad, should be lower...";
} else {
msg = "You got it... Nice work.";
}
var genderPrefix = $genderRadio.filter(':checked').val() === 'Male' ? 'Sir..' : 'Miss..';
msg = genderPrefix + msg;
}
$output.text(msg);
});
Check Fiddle
I will give an little introduction to javascript pattern with my example. you can read about them in http://addyosmani.com/resources/essentialjsdesignpatterns/book/ is not a easy reading but when you are ready you will understand pretty much about how to organize you javascript code with that book.
meanwhile I can advise you to read about how to code forms with good practices at http://net.tutsplus.com/tutorials/html-css-techniques/20-html-forms-best-practices-for-beginners/
Ok beside that here are the working example about how to work with click and forms http://jsfiddle.net/ncubica/BQaYz/
HTML
<label><input type="Radio" name="gender" id="male" value="male" /> male</label>
<label><input type="Radio" name="gender" id="female" value="female" />female</label>
<input type="text" id="name" placeholder="name" />
<input type="text" id="lastname" placeholder="lastname" />
<input type="button" id="submit" value="store" />
javascript
var survey = (function(_module){
var modulename = _module;
var user = {};
/*private methods*/
function init(){
observers();
}
function observers(){
$(document).on("click","#submit", survey.store)
}
/*public methods*/
$r = {}
$r.store = function(){
user.name = $("#name").val();
user.lastname = $("#lastname").val();
user.gender = $("input:radio[name=gender]:checked").val();
survey.toString();
}
$r.toString = function(){
var genderStr = (user.gender == "male") ? "Man" : "Girl";
alert(user.name + " " + user.lastname + " is " + genderStr);
}
$r.init = function(){
init();
}
return $r;
})("survey")
survey.init();
Ok, I know at first look a little "big" code but is really simple, in javascript a variable can take any kind of form from a function to a normal string.
here we are working with anonymous functions to create a module will help us to work more clear and structure, this variable will have 2 kind of methods and variable, public and privates.
for make a method public we have to return the methods in an object after we finish to run the code this is why exist the $r variable which is an object who have function by properties, and at the end of the code you return it doing return $r with this pattern now you can easily can navigate throw methods and catch events like click, change, etc....
you only should have to add this event to the method observers create a private or public function which will be activate after the event an you are done.
Read the code and if you have any further question you can ask me anything. I try to solve you problem and structure you code.
best good luck
[Here is below answer as a jsFiddle]
This answer is intended as a starter. I tried to write it at a beginner level, so that you can customize it for yourself. Hopefully, this simple example can give you a starting place. I used the example of a training gym asking some basic questions of their users.
My approach was to create an empty DIV, called #ques, where all Questions and output will be displayed, and a hidden <form> containing hidden fields that will store the responses.
I created a counter, cnt, which is incremented after each question.
There is a function called ask_next_ques() that takes the parameter cnt. Depending on where we are in the survey, it asks the next question (eg. when cnt==3 it asks the third question).
Unfortunately, javascript insists that all strings be on one line. Therefore, I built the html like this:
var qq = '
<ul style="list-style:none">
<li>
What can you curl?<br />
<input type="text" id="curl"> Kg
</li>
<li>
What can you bench?<br />
<input type="text" id="bench"> Kg
</li>
<li>
What can you lift?<br />
<input type="text" id="lift"> Kg
<input type="button" id="cbl_btn" value="Go">
</li>
</ul>
';
and then re-arranged it onto one line, like this:
var qq = '<ul style="list-style:none"><li>What can you curl?<br /><input type="text" id="curl"> Kg</li><li>What can you bench?<br /><input type="text" id="bench"> Kg</li><li>What can you lift?<br /><input type="text" id="lift"> Kg<input type="button" id="cbl_btn" value="Go"></li></ul>';
Much more difficult to read that way, but that's how javascript wants things.
As each question is answered, the responses are read by javascript/jQuery and then saved into hidden fields inside the <form> structure.
When all questions have been asked, you can just POST the form to another (PHP?) file for processing (storage in a MySQL database?), or email the answers to yourself, or re-display them to the user, or... I chose to display the answers in a lightbox.
Here is all the code. Just copy/paste it into a single HTML or PHP file, and run.
SURVEY.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" /><!--Lightbox-->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script><!--Lightbox-->
<style>
</style>
<script type="text/javascript">
//Declare vars outside document.ready() so they can be accessed globally
var ctr = 1;
var mf = '';
var pl = '';
$(document).ready(function() {
ask_next_ques(ctr);
/* ------------------------------------------------------------ */
$("input:radio[name=gender]").click(function() {
//Note: var mf must be initialized above (outside document.ready() ) so can be used in below fn ask_next_ques()
mf = $('input:radio[name=gender]:checked').val();
$('#hgender').val(mf);
ctr++;
ask_next_ques(ctr);
});
/* ------------------------------------------------------------ */
$(document).on('click', "#cbl_btn", function() {
var cc = $("#curl").val();
var bb = $("#bench").val();
var ll = $("#lift").val();
//alert('Value of cc: ' +cc+ ' Value of bb: ' +bb+ ' Value of ll: ' + ll);
//Check if any one of these fields left empty
if (cc.length<1 || bb.length<1 || ll.length<1) {
alert("Please complete all fields");
}else{
$('#hcurl').val(cc);
$('#hbench').val(bb);
$('#hlift').val(ll);
ctr++;
ask_next_ques(ctr);
}
});
/* ------------------------------------------------------------ */
$(document).on('click', "input:radio[name=plan]", function() {
//Note: var pl must be initialized above so can be used in below fn ask_next_ques()
pl = $('input:radio[name=plan]:checked').val();
$('#hplan').val(pl);
ctr++;
ask_next_ques(ctr);
});
/* ------------------------------------------------------------ */
}); //END $(document).ready()
function ask_next_ques(ctr) {
if (ctr==1) {
var qq = 'Male: <input value="Male" type="radio" name="gender"><br />Female: <input value="Female" type="radio" name="gender">';
$('#ques').html(qq);
}else if (ctr==2){
var qq = '<ul style="list-style:none"><li>What can you curl?<br /><input type="text" id="curl"> Kg</li><li>What can you bench?<br /><input type="text" id="bench"> Kg</li><li>What can you lift?<br /><input type="text" id="lift"> Kg<input type="button" id="cbl_btn" value="Go"></li></ul>';
$('#ques').html(qq);
}else if (ctr==3){
var qq = 'Are you an:<br />Owner: <input value="Owner" type="radio" name="plan"><br />Member: <input value="Member" type="radio" name="plan">';
$('#ques').html(qq);
}else if (ctr==4){
//All questions have been asked; All responses saved into hidden fields
//Can now read all hidden fields and do an AJAX POST into the database, or
//Or can simply POST the form to another page for processing.
alert("All questions have been asked");
var hg = $('#hgender').val();
var hc = $('#hcurl').val();
var hb = $('#hbench').val();
var hl = $('#hlift').val();
var hp = $('#hplan').val();
qq = 'The values saved into all hidden fields are:<br />Gender: ['+hg+ ']<br />Curl: [' +hc+ ']<br />Bench: [' +hb+ ']<br />Lift: [' +hl+ ']<br />Plan: [' +hp+ ']<br />You can now send these values to a<br />database, or email them to yourself.';
$('#ques').html(qq);
//We could just leave it here, but to be interesting we'll display the results in a lightbox
//To remove all lightbox stuff, just delete the next 8 lines and delete the two lightbox references in the header (for jquery-ui)
$('#ques').dialog({
autoOpen:true,
width: 450,
title: "Hidden Field Valuess:",
close: function() {
alert('Thank you for taking our survey');
}
});
}
}
</script>
</head>
<body>
<div id="ques"></div>
<div id="hidden_form">
<form method="POST">
<input type="hidden" id="hgender" name="gender">
<input type="hidden" id="hcurl" name="curl">
<input type="hidden" id="hbench" name="bench">
<input type="hidden" id="hlift" name="lift">
<input type="hidden" id="hplan" name="owner">
</form>
</div>
</body>
</html>

jquery code to change the parameters submitted by a form

In a web form in a PHP program, the form is a regular HTML form.
Now, the form has 3 separate text boxes. Let their IDs/names be box1, box2 and box3 respectively
What I want to happen is, when the form gets posted --
The following text gets posted--> box1 + box2+ box3 contents, separated by commas.
I wish to do this using JQuery- I looked up JQuery "submit" function but could not find any direct way to replace the parameters-- how can I implement the above?
You could do this :
$('#yourForm').submit(function(e){
var form = $(this)
//Do you validation
if(isValid){
var mergedInput = $('<input/>');
var inputToMerge = ['#box1','#box2','#box3'];
var valueToMerge = $.map(inputToMerge, function(selector){
val = $(selector).val()
$(selector).remove()
return val;
})
mergedInput.val(valueToMerge.join(','));
mergedInput.prop('name', 'mergedInput')
mergedInput.appendTo(form);
}else{
return false;
}
})
Basicly, it is merging your input into one accessible via php with ['mergedInput'].
i think you can do this easily using ajax .. Kindly check Change contents of submitted form on submit
if you want to do this without ajax, you may have to use hidden fields .. Kindly check jquery-add-additional-parameters-on-submit-not-ajax
You can use AJAX to solve your problem
Your HTML
<form onsubmit="return sendBoxes()">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="submit">
</form>
And JS
function sendBoxes(){
var values = "'"+$('#box1').val()+"'"+$('#box2').val()+"'"+$('#box3').val()+"'";
jQuery.ajax({
url: "ajax_ajax.php",
data: "boxes="+values,
cache: false,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error.\n" + textStatus + " " + errorThrown);
}
});
return false;
}
HTML
<input id="box1" type="text" />
<input id="box2" type="text" />
<input id="box3" type="text" />
<input id="submit_button" type="submit" />
JS
function submit(){
$.ajax({
type: "POST",
url: "someurl.php",
data:{'boxes':$('#box1').val()+","+$('#box2').val()+","+$('#box3').val()}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
$("#submit_button").click(function(e) {
submit();
e.preventDefault();
return false;
});
This would check whether submit button is clicked and sends three box values separated by comma

Dynamic Form Input Based on Anchor Value

I have the following snippets that open a single Modal Form:
<a class="modalbox" id="foo" href="#inline">Request a Quote</a>
<a class="modalbox" id="bar" href="#inline">Request a Quote</a>
...and so on...
Somehow, I need to render the value of ID in the input "sub" in the following HTML form
as well as concatenate the ID with some predetermined text, which is "I am interested in..."
<form id="contact" name="contact" action="#" method="post">
<input type="hidden" id="product" name="product" value="">
<label for="sub">Subject:</label>
<input type="sub" id="sub" name="sub" class="txt" value="I am interested in '$id'">
<button id="send">Submit</button>
I'm already using Javascript for verification and AJAX for processing to PHP script.
Edit:
This is the Javascript already being used to populate the hidden input above, which is working perfectly:
$('a').click(function(e) {
$('#product').val($(this).attr('id'));
I'd suggest, with plain JavaScript, something like:
function addTextToInput(from, to, prefix, e) {
e = e || window.event;
if (!from || !to) {
return false;
}
else {
from = from.nodeType == 1 ? from : document.getElementById(from);
to = to.nodeType == 1 ? to : document.getElementById(to);
var text = from.id;
to.value = prefix ? prefix + ' ' + text : text;
}
}
var as = document.querySelectorAll('a.modalbox');
for (var i = 0, len = as.length; i<len; i++) {
as[i].onclick = function(e) {
addTextToInput(this, 'sub', 'I am interested in', e);
};
}​
JS Fiddle demo.
But given that you already seem to be using jQuery:
$('a.modalbox').click(function(e){
e.preventDefault();
$('#sub').val('I am interested in ' + this.id);
});
JS Fiddle demo.

Form Hidden Field Substitution

I'm building a form using Expression Engine's Safecracker module.
One of the the required fields is the Title, which becomes the title of the EE channel entry.
What I'd like to do is set the Title field to be the combined first name and last name fields.
I started with this:
<form method="POST" action="#">
<input id="student_first_name" type="text" size="30" name="student_first_name">
<br>
<input id="student_last_name" type="text" size="30" name="student_last_name">
<br><br>
<input type="text" name="title" value=""/>
</form>
And then added this:
$(function() {
$('#student_first_name').keyup(function() {
var snamef = $(this);
});
$('#student_last_name').keyup(function() {
var snamel = $(this);
});
$("input[name='title']").val(snamel + " " + snamef);
return false;
});​
​I can't get it to work, though: http://jsfiddle.net/tylonius/CY5zJ/4/
Am I missing a step (or just totally doing it wrong?)?
Also, am I possibly working too hard and Safecracker already has this function built in; similar to its live UrlTitle(); function?
Any help is appreciated.
Thanks,
ty
If I understood right your question try this:
First set an id on your desired input element, like this :
<input type="text" name="title" id="student_title" value=""/>
And then :
$(function() {
changeFunction = function() {
$('#student_title').val($('#student_first_name').val() + ' ' + $("#student_last_name").val());
}
$('#student_first_name').keyup(changeFunction)
$('#student_last_name').keyup(changeFunction);
});
Better yet, avoid using javascript altogether and just use SafeCracker's dynamic_title parameter.
dynamic_title="[student_first_name] [student_last_name]"
user1236048 has the best solution for you but below is a working version of your code
$(function() {
var snamef;
var snamel;
$('#student_first_name').keyup(function() {
snamef = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
$('#student_last_name').keyup(function() {
snamel = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
return false;
});
and here is the working jsfiddle

Categories

Resources