Is it possible to get dynamic values in a form with jQuery?
For example I have this:
<form id="contact" method="post" action"contact.php" class="ajaxForm">
<label>Name:</label>
<input type="text" name="name" />
<label>Email:</label>
<input type="text" name="email"/>
<label>Message:</label>
<textarea name="message"></textarea>
<input type="submit" value="send!"/>
</form>
In js:
$(".ajaxForm").send(function(){
var page = $(this).attr("action");
});
I want to get var name=value with some loop like .each but the code is only reading inputs/textarea/select data.
Thanks for the help!
You can obtain input/textarea/select values in a form with jQuery.
$(".ajaxForm").send(function(){
var page = $(this).attr("action");
var its = $(this).find('input, textarea, select');
its.each(function(){
console.log($(this).val());
})
});
Use .children()
$(".ajaxForm").send(function(){
var page = $(this).attr("action");
$(this).children('input').each(function() { // Loop over all the children
// that are input elements
console.log( $(this).val() );
OR
console.log( this.value );
});
});
Related
jQuery(function ($) {
var submitbnt = '<input type="button" id="submit" class="btn btn-primary pull-right" value="Submit" />';
var formData = '[{"type":"select","label":"Select","className":"form-control","name":"select-1498804267849","values":[{"label":"Option 1","value":"option-1"},{"label":"Option 2","value":"option-2","selected":true},{"label":"Option 3","value":"option-3"}]},{"type":"text","label":"Text Field","className":"form-control","name":"text-1498804394861","subtype":"text"},{"type":"text","label":"Text Field","className":"form-control","name":"text-1498804395129","subtype":"text"}]';
formRenderOpts = {
dataType: 'json',
formData:formData
}
$('#mform').formRender(formRenderOpts);
$('#mform').append(submitbnt);
document.getElementById('submit').onclick = function () {
var formData = new FormData(document.forms[0]);
var result = {};
for(var pair of formData.entries()) {
result[pair[0]] = pair[1];
}
console.log($('#mform').formData());
result = JSON.stringify(result); // just key/ value
var htmlForm = $('#mform').html(); // Can not get merge values in code
};
});
<h1>Form demo</h1>
<form class="col-md-12" id="mform" style="background-color:white;padding:50px">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="http://formbuilder.online/assets/js/form-builder.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-render.min.js"></script>
I use the formbuilder of http://formbuilder.readthedocs.io. I render a form. And show that form, then I input the data, and I want to get the html code of that form, I have found many ways but only I can not get the html code of form and values. I only get the html code, but no values. Or I just get the values but no html, I think I will have to manually "mix" the values that I get into the html code. But actually it is very troublesome.
I have a registration form, I want when the user click on the submit button will get all the html code of the form tag, it includes all input, drop-down list, radio, button .. and value already was inputed.
I tried using $('#myform').html() to get all the form's code, but it did not get the values that I entered into the input, or radio ...
I want to get something like this:
<form id="myForm" class="cusForm">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
Try serialize() function of jquery
console.log($('form').serialize())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" class="cusForm">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
I don't know why you need the html, just in case you need the values of properties that are being post you can check this code, you will get array of the values which are being posted,
$(function(){
$('.submit').click(function(){
var result = [];
$('#myForm input').each(function(e,v){
var value = {};
value.property = v.name;
value.value = v.value;
result.push(value);
});
alert(JSON.stringify(result));
});
});
Working Fiddle: https://jsfiddle.net/jks7afpx/
You can use $('#myForm').serializeArray() and $('#myForm input:text'); to get data and text type input's html of your form.
$("#getTextInputs").on("click", function(){
console.clear();
var textInputs = $('#myForm input:text');
$.each(textInputs, function(){
$(this).attr("value", $(this).val());
console.log(this);
})
})
$("#getFormData").on("click", function(){
console.clear();
var data = $('#myForm').serializeArray();
console.log(data);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" class="cusForm">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="button" id="getTextInputs" value="Get Text Input Html">
<input type="button" id="getFormData" value="Get Form Data">
</form>
What I am trying to accomplish: When a user inputs dates, number of adults ect it would dynamically add the info via javascript to the URL within the url variables. This is what I have so far: ( I am a Noob but trying to make it work )
<script type="text/javascript">
$(function () {
$('#submit').click(function() {
$('#button').click(function(e) {
var checkInDate = document.getElementById('checkInDate').value;
var checkInMonthYear = document.getElementById('checkInMonthYear').value;
var checkOutDate = document.getElementById('checkOutDate').value;
var checkOutMonthYear = document.getElementById('checkOutMonthYear').value;
var numberOfAdults = document.getElementById('numberOfAdults').value;
var rateCode = document.getElementById('rateCode').value
window.location.replace("http://www.Link.com/redirect?path=hd&brandCode=cv&localeCode=en®ionCode=1&hotelCode=DISCV&checkInDate=27&checkInMonthYear=002016&checkOutDate=28&checkOutMonthYear=002016&numberOfAdults=2&rateCode=11223");
window.location = url;
});
});
Ok, so first things first: You probably don't need to do this at all. If you create a form and add a name attribute to each input, then the submission automatically creates the URL for you. Fixed value fields can be set to type="hidden".
For this to work you need to use the "GET" method.
<form action="http://www.Link.com/redirect" method="GET">
<input type="hidden" name="path" value="hd"><br>
<input type="hidden" name="brandCode" value="cv"><br>
<input type="hidden" name="localeCode" value="en"><br>
<input type="hidden" name="regionCode" value="1"><br>
<input type="hidden" name="hotelCode" value="DISCV"><br>
<input type="text" name="checkInDate"><br>
<input type="text" name="checkInMonthYear"><br>
<input type="text" name="checkOutDate"><br>
<input type="text" name="checkOutMonthYear"><br>
<input type="text" name="numberOfAdults"><br>
<input type="text" name="rateCode"><br>
<input type="submit">
</form>
Clicking "Submit" changes the URL to the desired one.
If this does not suit your needs, you can replace parameters in the URL by following the advice in this SO answer: Answer Link
This is much better than trying to re-implement URL manipulation on your own.
I'm having a form looks like this:
<form method="POST">
<input type="text" name="htdate" id="htdate">
<br/>
<input type="text" name="pgdate" name="pgdate">
<br/>
<input type="submit" name="submit" value="submit">
</form>
I would like get the textbox id when on form change. My js code looks like this:
$('form :input').change(function()
{
var eleID = $(this).id;
console.log("changeID: ", eleID);
});
Console output :
changeID: undefined
Is there any ways to get the id of the element during value change.?
id is the property of dom object and jQuery object doesn't have any id property, so it will always return undefined
Use this.id or $(this).attr('id') to get id of the element
$('form :input').change(function() {
var eleID = this.id;
// var eleID = $(this).attr('id');
console.log("changeID: ", eleID);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="htdate" id="htdate">
<br/>
<input type="text" name="pgdate" name="pgdate">
<br/>
<input type="submit" name="submit" value="submit">
</form>
If you want to listen inputting value then use keypress , keyup or input event
$('form :input').on('input', function() {
var eleID = this.id;
// var eleID = $(this).attr('id');
console.log("changeID: ", eleID);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="htdate" id="htdate">
<br/>
<input type="text" name="pgdate" name="pgdate">
<br/>
<input type="submit" name="submit" value="submit">
</form>
use $().attr();
$('form :input').change(function()
{
var eleID = $(this).attr("id");
console.log("changeID: ", eleID);
});
Is there any ways to get the id of the element during value change.?
For this you can use input event which is introduced in the html5. so this can be done:
$('form :input').on('input', function()
{
var eleID = this.id; // <----this.id; || $(this).attr('id');
console.log("changeID: ", eleID);
});
change event only gets invoked when you loose focus from the input so if you are looking for immediate effect while typing/cut-copy-paste then input would be beneficial for you.
I have a simple form, with one issue.
In explorer, if nothing is inserted, the placeholder is passed as input of the field.
Here is JSbin: http://jsbin.com/EvohEkO/1/
I would like to make a simple comparision, when form is submitted, to check if the value of the field is equal to "First name", and if yes make the value empty ""
Just this i need.
Someone can help me please?
<form onsubmit="return checkform()">
<input name="test" placeholder="placeholdertext" id="test" />
<input type="submit" value="submitbutton"/>
</form>
in js
you should import jquery latest version this is the link: http://code.jquery.com/jquery-1.10.2.min.js
function checkform(){
var fieldvalue = $.trim($('#test').val());
if(!fieldvalue || fieldvalue=="placeholdertext"){
alert('there is no input');
return false;
}else{
alert('enjoy your form!');
return true;
}
}
This is somewhat easier..
$(document).ready(function(){
$("#form").submit(function(){
$('#form input:text, textarea').each(function() {
if($(this).val()==$(this).attr('placeholder'))
$(this).val(" ");
});
});
});
Just put your field value in hidden type input like this :-
<input id="hdnfield" name="hdnfield" value="<Your Field Value>" />
To check the value of a form field use the val() function on the input element
var input_value = jQuery('Input Element Selector').val();
As I looked to your form, the elements do not have any id attribute, I recommend that you add one to each of them, also change the submit input to button the you have more control on the javascript. so your form will look like :
<form id="form" action="form.php" method="post">
<input id="fname" type="text" placeholder="First name" name="fname"><br>
<label for="fname" id="fnamelabel"></label>
<input id="lname"type="text" placeholder="Last name" name="lname"><br>
<textarea id="message" placeholder="Contact us!" cols="30" rows="5" name="message"></textarea><br>
<br>
<input type="button" value="Submit">
</form>
so your jQuery will look like:
jQuery(document).ready(function(){
jQuery('input[type="button"]').click(function(){
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
var message = jQuery('#message').val();
...... Do whatever you need & then change the input values
...... if all validation has passed the use jQuery('#form').submit(); to submit the form otherwise reset the form:
jQuery('#fname').val("");
jQuery('#lname').val("");
jQuery('#message').val("");
});
});
here is a working version:
jsfiddle working link
You can do it like the following!
<form>
<input type="text" id="first_name" name="first_name"/>
<input type="submit" id="submit" value="submit"/>
</form>
<script type="type/javascript"/>
jQuery.noConflict();
(function ($) {
$(function () {
$("#submit").click(function () {
if ($("#first_name").val() == "first name") {
$(this).val("");
}
});
});
})(jQuery);
</script>
I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>