How to serialize form in jquery while having it as object - javascript

I already have form object like this in a variable:
<form method="post" id="modal_form1" action="http://localhost/bookmark/post_crud_model_form">...</form>
How can I serialize it using jQuery only?
JS
function submit_form(form){
var se = String(form);
console.log($(se).serialize());
}
Form in Console
<form method="post" id="modal_form1" action="http://localhost/bookmark/post_crud_model_form"><input type="hidden" id="input1" value="1"><div class="form-group">
<label for="recipient-name" class="col-form-label">Link</label>
<input type="text" class="form-control" id="input1" value="FIRST LINK"></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Category</label><select class="form-control"><option>cat 1</option><option value="1">cat 1</option><option value="2">cat 2</option><option value="3">cat 3</option><option value="4">cat 4</option></select></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Detail</label>
<input type="text" class="form-control" id="input1" value="ASDASDASASF"></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Created_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21"></div><div class="form-group">
<label for="recipient-name" class="col-form-label">Updated_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21"></div><div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="submit_form(this.form);" class="btn btn-primary">Send message</button>
</div></form>
HTML
<button type="button" onclick="submit_form(this.form);" class="btn btn-primary">Send message</button>
</div>';
$return .= '</form>';

There are two issues in your code. Firstly you're sending a Form Element object to the submit_form() function which you then attempt to coerce to a string. This is the source of your error. If you skip that step, the jQuery object can be created correctly.
Secondly to serialise data in a form all the fields must have name attributes on them, so you need to amend your HTML. Once those points are addressed, the logic works fine.
Also note that I changed the button to a submit so that the form is submit and then hooked a an unobtrusive event handler to listen for that event on the form. You should not be using on* event attributes at all as they are incredibly outdated.
$('#modal_form1').on('submit', function(e) {
e.preventDefault();
console.log($(this).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="modal_form1" action="http://localhost/bookmark/post_crud_model_form"><input type="hidden" id="input1" value="1">
<div class="form-group">
<label for="recipient-name" class="col-form-label">Link</label>
<input type="text" class="form-control" id="input1" value="FIRST LINK" name="link"></div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Category</label>
<select class="form-control" name="category">
<option>cat 1</option>
<option value="1">cat 1</option>
<option value="2">cat 2</option>
<option value="3">cat 3</option>
<option value="4">cat 4</option>
</select>
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Detail</label>
<input type="text" class="form-control" id="input1" value="ASDASDASASF" name="detail"></div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Created_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21" name="created_at"></div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Updated_at</label>
<input type="text" class="form-control" id="input1" value="2019-01-12 22:25:21" name="updated_at"></div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="send_message">Send message</button>
</div>
</form>

Related

form loading despite of using e.preventDefault();

I am making an ajax form but the problem is that form is loading despite using e.preventDefault(). I have googled a lot and found the most answer but still not working.
$(document).ready(function() {
$("#upload").on('submit', function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="input-email">Product Name</label>
<input type="text" name="ProductNamees" value="" placeholder="Enter Product Name" id="Product" class="form-control">
</div>
<div class="form-group">
<label class="control-label" for="input-email">Category</label>
<select name="category" name="category" value="" id="category" class="form-control">
<option value="0">Category</option>
<option value="1">Flower Bouquet (Buke)</option>
<option value="2">Flower Garland (Har)</option>
<option value="3">Stage Decoration</option>
<option value="4">Bed Decoration</option>
<option value="5">Car Decoration</option>
<option value="6">Home Decoration</option>
<option value="7">Palna Decoration</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="input-email">file upload</label>
<input type="file" name="files" value="" placeholder="" id="file" class="form-control">
</div>
<div class="form-group">
<label class="control-label" for="input-email">price</label>
<input type="text" name="price" value="" placeholder="Enter price" id="price" class="form-control">
</div>
<input type="submit" id="uploadsdfkf" name="upload" value="upload" class="btn check btn-primary">
</form>

auto fill other fields when a select option is selected in handlebars

i have a modal that looks like this and i wanna auto fill the price input value whenever i choose a product from the article list. How do I go about to achieve this ? Thank you
<div class="modal-body">
<div>
<label for="type">article</label>
<select id="article" name="article" class="form-control">
{{#each articles}}
<option>{{name}}</option>
{{/each}}
</select>
</div>
<input type="text" class="form-control" name="desc" id="desc" placeholder="Description" value="{{desc}}">
<input type="text" class="form-control" name="quantity" id="quantity" placeholder="Qté commandée" value="{{quantity}}">
<input type="text" class="form-control" name="price" id="price" placeholder="Prix Unitaire" value="{{price}}">
<input type="text" class="form-control" name="tax" id="tax" placeholder="Taxes" value="{{tax}}">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Quité</button>
<button type="button" name="add" id="add" onclick="isValid()" class="btn btn-primary" data-dismiss="modal">Ajouter</button>
</div>
any help ??
I didn't test it, but something like this..?
<div class="modal-body">
<div>
<label for="type">article</label>
<select id="article" name="article" class="form-control">
{{#each articles}}
<option data-price="{{price}}">{{name}}</option>
{{/each}}
</select>
</div>
<input type="text" class="form-control" name="desc" id="desc" placeholder="Description" value="{{desc}}">
<input type="text" class="form-control" name="quantity" id="quantity" placeholder="Qté commandée" value="{{quantity}}">
<input type="text" class="form-control" name="price" id="price" placeholder="Prix Unitaire" value="{{price}}">
<input type="text" class="form-control" name="tax" id="tax" placeholder="Taxes" value="{{tax}}">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Quité</button>
<button type="button" name="add" id="add" onclick="isValid()" class="btn btn-primary" data-dismiss="modal">Ajouter</button>
</div>
<script>
$(document).ready(function () {
$('#article').change(function () {
var price = $(this).find(':selected').attr('data-price');
$('#price').attr('value', price);
});
});
</script>

Hide/Show multiple textfields based on select option

Im using bootstrap 4, html, css, js the lot when trying to do this.
I'm trying to show some text boxes depending on the choice of the select option.
So if I choose "adadelta" I'd like to have only 4 specific text boxes(number type) show and everything else remain hidden. Should mention that the below form in hosted in a popover window which works fine, as such I've only included the form itself.
I've tried various javascript examples for similar situations but its just not showing the text boxes even when I try document.getElementById etc.
Any suggestions would be much appreciated.
<form>
<div class="form-group">
<label for="epochEdit">Epochs:</label>
<input type="number" class="form-control" id="epochEdit">
<label for="batchEdit">Batch Size:</label>
<input type="number" class="form-control" id="batchEdit">
</div>
<div class="form-group">
<label for="optChoose">Optimizer:</label>
<select class="form-control" id="optChoose">
<option selected>Open this menu</option>
<option value="sgd">sgd</option>
<option value="adadelta">adadelta</option>
<option value="rmsprop">rmsprop</option>
<option value="adam">adam</option>
<option value="adamax">adamax</option>
<option value="adagrad">adagrad</option>
<option value="nadam">nadam</option>
</select>
</div>
<div class="form-group">
<fieldset disabled>
<div class="form-group">
<label for="disabledNote">Note:</label>
<input type="text" id="disabledNote" class="form-control" placeholder="Optimizers will use keras default values!">
</div>
</fieldset>
<label for="lr">Learning Rate:</label>
<input type="number" class="form-control" id="lr">
<label for="rho">Rho:</label>
<input type="number" class="form-control" id="rho">
<label for="epsilon">Epsilon:</label>
<input type="number" class="form-control" id="epsilon">
<label for="decay">Decay:</label>
<input type="number" class="form-control" id="decay">
<label for="b1">Beta #1:</label>
<input type="number" class="form-control" id="b1">
<label for="b2">Beta #2:</label>
<input type="number" class="form-control" id="b2">
<label for="sDecay">Schedule Decay:</label>
<input type="number" class="form-control" id="sDecay">
<label for="moment">Momentum:</label>
<input type="number" class="form-control" id="moment">
<label for="nesterov">Nesterov:</label>
<input type="checkbox" class="form-check-input" id="nesterov">
</div>
<button id="subSettings" class="bg-color-3 btn btn-info"> Submit </button>
</form>
Try this
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
var el = '<label for="lr">Learning Rate:</label>\
<input type="number" class="form-control" id="lr">\
\
<label for="rho">Rho:</label>\
<input type="number" class="form-control" id="rho">\
\
<label for="epsilon">Epsilon:</label>\
<input type="number" class="form-control" id="epsilon">\
\
<label for="decay">Decay:</label>\
<input type="number" class="form-control" id="decay">\
\
<label for="b1">Beta #1:</label>\
<input type="number" class="form-control" id="b1">\
\
<label for="b2">Beta #2:</label>\
<input type="number" class="form-control" id="b2">\
\
<label for="sDecay">Schedule Decay:</label>\
<input type="number" class="form-control" id="sDecay">\
\
<label for="moment">Momentum:</label>\
<input type="number" class="form-control" id="moment">';
function select() {
var optSel = $("#optChoose").val();
appendControls(optSel);
}
function appendControls(num) {
$('#elcontainer').empty();
if (num == "adadelta") {
$('#elcontainer').append(el);
}
}
</script>
</head>
<body>
<div class="container">
<h2>Form control: input</h2>
<p>The form below contains two input elements; one of type text and one of type password:</p>
<div class="form-group">
<label for="epochEdit">Epochs:</label>
<input type="number" class="form-control" id="epochEdit">
<label for="batchEdit">Batch Size:</label>
<input type="number" class="form-control" id="batchEdit">
</div>
<div class="form-group">
<label for="optChoose">Optimizer:</label>
<select class="form-control" id="optChoose" onchange="select();">
<option value="">Open this menu</option>
<option value="sgd">sgd</option>
<option value="adadelta">adadelta</option>
<option value="rmsprop">rmsprop</option>
<option value="adam">adam</option>
<option value="adamax">adamax</option>
<option value="adagrad">adagrad</option>
<option value="nadam">nadam</option>
</select>
</div>
<div class="form-group">
<fieldset disabled>
<div class="form-group">
<label for="disabledNote">Note:</label>
<input type="text" id="disabledNote" class="form-control"
placeholder="Optimizers will use keras default values!">
</div>
</fieldset>
<div id="elcontainer"></div>
<label for="nesterov">Nesterov:</label>
<input type="checkbox" class="form-check-input" id="nesterov">
</div>
<button id="subSettings" class="bg-color-3 btn btn-info"> Submit</button>
</div>
</body>

Display extra form fields if dropdown is selected

I'm trying to make two extra form fields appear if the user selects 'Yes' from a dropdown. If the user does not select 'Yes' from the dropdown, then the two extra fields are not required and are disabled, however if 'Yes' is selected these fields must be filled in before form submission. I have this so far, however it's not working. If anyone could point out the issue it would be greatly appreciated.
HTML:
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>
</div>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>
JavaScript:
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
document.getElementById('extra').style.display = '';
document.getElementById('auth_by').disabled = false;
document.getElementById('desc').disabled = false;
} else {
document.getElementById('extra').style.display = 'none';
}
}
JSFiddle
checkIfYes needs to be defined before the HTML that references it.
I would also recommend changing the select onclick event to onchange so that it only gets called when the user actually changes he value
See updated fiddle : Updated Fiddle
<script>
function checkIfYes() {
if (document.getElementById('defect').value == 'Yes') {
document.getElementById('extra').style.display = '';
document.getElementById('auth_by').disabled = false;
document.getElementById('desc').disabled = false;
} else {
document.getElementById('extra').style.display = 'none';
}
}
</script>
<form id="form" method="post" action="action.php">
<div class="form-group">
<label class="control-label">Defect?</label>
<select onchange='checkIfYes()' class="select form-control" id="defect" name="defect">
<option id="No" value="No">No</option>
<option id="Yes" value="Yes">Yes</option>
</select>
</div>
<div id="extra" name="extra" style="display: none">
<label class="control-label" for="desc">Description</label>
<input class="form-control" type="text" id="desc" name="desc" required disabled>
<label class="control-label" for="auth_by">Authorised By</label>
<input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>
</div>
<div class="form-group">
<button class="btn btn-info" id="submit" name="submit" type="submit">Submit
</button>
</div>
</form>

How to get attributes values on change of select dropdown

I have a select dropdown of addresses on change of select dropdown I need to get option attributes and paste them in input fields.
Here is what I tried so far TryFiddle
I have data attributes as data-address, data-city, data-zipcode and data-country for each option, when I select any option I want that options data-attr to be pasted in respective input boxes;
here is my code
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
alert('change');
$("#bill_address").val($(this).attr('data-address'));
$("#bill_city").val($(this).attr('data-city'));
$("#bill_zipcode").val($(this).attr('data-zipcode'));
$("#bill_country").val($(this).attr('data-country'));
})
})
Html code
<div id="collapseOne" class="panel-collapse collapse in">
<form role="form" onsubmit="event.preventDefault();" action="#" method="post" class="billing-form" id="billing-form">
<div class="form-group">
<select name="" class="form-control" id="saved_billing_addresses">
<option value="">Select Address</option>
<option value="" data-address="Koramangala" data-city="Bangalore" data-zipcode="216521" data-country="India">Koramangala, Banglore, 211322, India</option>
<option value="" data-address="Shivaji nagar" data-city="Mumbai" data-zipcode="123455" data-country="India">Shivaji Nagar, Mumbai, 123455, India</option>
<option value="" data-address="Ambedkar nagar" data-city="Kolkata" data-zipcode="567890" data-country="India">Ambedkar Nagar, Kolkata, 567890, India</option>
</select>
</div>
<div class="form-group">
<textarea autofocus class="f-bill bill_address form-control form-group" placeholder="* Address" name="billing[address]" id="bill_address" cols="30" rows="3"></textarea>
</div>
<div class="form-group">
<input type="text" name="billing[city]" placeholder="* City" class="f-bill bill_city form-control" id="bill_city" value="">
</div>
<div class="form-group">
<input type="text" name="billing[zip_code]" placeholder="* Zipcode" class="f-bill bill_zipcode form-control" id="bill_zipcode" value="">
</div>
<div class="form-group">
<input type="text" name="billing[country]" placeholder="* Country" class="bill_country f-bill form-control" id="bill_country" value="">
</div>
<div class="form-group" style="width:150px;float:left;">
<button type="submit" id="next_check" class="btn btn-next pull-right btn-success bill-ship-btn">Next</button>
</div>
</form>
</div>
</div>
I dont know whats going wrong it should work, please provide any suggestions
This is one of the rare places where jQuery doesn't do much for you, your best bet is to use the select box's native selectedIndex property and options collection:
// Get the selected HTMLOptionElement
var opt = this.options[this.selectedIndex];
E.g.: (updated fiddle)
$(document).ready(function() {
$('#saved_billing_addresses').on("change", function() {
var opt = this.options[this.selectedIndex];
if (opt) {
opt = $(opt);
$("#bill_address").val(opt.attr('data-address'));
$("#bill_city").val(opt.attr('data-city'));
$("#bill_zipcode").val(opt.attr('data-zipcode'));
$("#bill_country").val(opt.attr('data-country'));
}
})
});
Try it..
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
$("#bill_address").val($('option:selected', this).data('address'));
$("#bill_city").val($('option:selected', this).data('city'));
$("#bill_zipcode").val($('option:selected', this).data('zipcode'));
$("#bill_country").val($('option:selected', this).data('country'));
})
});
.hide-it{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<div id="collapseOne" class="panel-collapse collapse in">
<form role="form" onsubmit="event.preventDefault();" action="#" method="post" class="billing-form" id="billing-form">
<div class="form-group">
<select name="" class="form-control" id="saved_billing_addresses">
<option value="">Select Address</option>
<option value="" data-address="Koramangala" data-city="Bangalore" data-zipcode="216521" data-country="India">Koramangala, Banglore, 211322, India</option>
<option value="" data-address="Shivaji nagar" data-city="Mumbai" data-zipcode="123455" data-country="India">Shivaji Nagar, Mumbai, 123455, India</option>
<option value="" data-address="Ambedkar nagar" data-city="Kolkata" data-zipcode="567890" data-country="India">Ambedkar Nagar, Kolkata, 567890, India</option>
</select>
</div>
<div class="form-group">
<textarea autofocus class="f-bill bill_address form-control form-group" placeholder="* Address" name="billing[address]" id="bill_address" cols="30" rows="3"></textarea>
</div>
<div class="form-group">
<input type="text" name="billing[city]" placeholder="* City" class="f-bill bill_city form-control" id="bill_city" value="">
</div>
<div class="form-group">
<input type="text" name="billing[zip_code]" placeholder="* Zipcode" class="f-bill bill_zipcode form-control" id="bill_zipcode" value="">
</div>
<div class="form-group">
<input type="text" name="billing[country]" placeholder="* Country" class="bill_country f-bill form-control" id="bill_country" value="">
</div>
<div class="form-group" style="width:150px;float:left;">
<button type="submit" id="next_check" class="btn btn-next pull-right btn-success bill-ship-btn">Next</button>
</div>
</form>
</div>
</div>
You have some typos:
$(this) within change event is not $(this).find(':selected')
.data('address') could be used for attr('data-address')
event handler within the same event handler is useless
whenever possible you can cache selected elements
My proposal is:
$(function () {
$('#saved_billing_addresses').on("change", function(e){
var jqSelectedOption = $(this).find(':selected');
$("#bill_address").val(jqSelectedOption.data('address'));
$("#bill_city").val(jqSelectedOption.data('city'));
$("#bill_zipcode").val(jqSelectedOption.data('zipcode'));
$("#bill_country").val(jqSelectedOption.data('country'));
});
});
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<div id="collapseOne" class="panel-collapse collapse in">
<form role="form" onsubmit="event.preventDefault();" action="#" method="post" class="billing-form" id="billing-form">
<div class="form-group">
<select name="" class="form-control" id="saved_billing_addresses">
<option value="">Select Address</option>
<option value="" data-address="Koramangala" data-city="Bangalore" data-zipcode="216521" data-country="India">Koramangala, Banglore, 211322, India</option>
<option value="" data-address="Shivaji nagar" data-city="Mumbai" data-zipcode="123455" data-country="India">Shivaji Nagar, Mumbai, 123455, India</option>
<option value="" data-address="Ambedkar nagar" data-city="Kolkata" data-zipcode="567890" data-country="India">Ambedkar Nagar, Kolkata, 567890, India</option>
</select>
</div>
<div class="form-group">
<textarea autofocus class="f-bill bill_address form-control form-group" placeholder="* Address" name="billing[address]" id="bill_address" cols="30" rows="3"></textarea>
</div>
<div class="form-group">
<input type="text" name="billing[city]" placeholder="* City" class="f-bill bill_city form-control" id="bill_city" value="">
</div>
<div class="form-group">
<input type="text" name="billing[zip_code]" placeholder="* Zipcode" class="f-bill bill_zipcode form-control" id="bill_zipcode" value="">
</div>
<div class="form-group">
<input type="text" name="billing[country]" placeholder="* Country" class="bill_country f-bill form-control" id="bill_country" value="">
</div>
<div class="form-group" style="width:150px;float:left;">
<button type="submit" id="next_check" class="btn btn-next pull-right btn-success bill-ship-btn">Next</button>
</div>
</form>
</div>
This is what you need.
$('#saved_billing_addresses').on("change",function(event){
const $this = this.options[this.selectedIndex];
$("#bill_address").val($this.getAttribute('data-address'));
$("#bill_city").val($this.getAttribute('data-city'));
$("#bill_zipcode").val($this.getAttribute('data-zipcode'));
$("#bill_country").val($this.getAttribute('data-country'));
});
You can also use the find to get the data attributes
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
$("#bill_address").val($(this).find(':selected').data('address'));
$("#bill_city").val($(this).find(':selected').data('city'));
$("#bill_zipcode").val($(this).find(':selected').data('zipcode'));
$("#bill_country").val($(this).find(':selected').data('country'));
})
});
Why you added two on Change events functions,Please remove second one. Try this..
$(document).ready(function(){
$('#saved_billing_addresses').on("change",function(){
$("#bill_address").val($(this).find('option:selected').attr('data-address'));
$("#bill_city").val($(this).find('option:selected').attr('data-city'));
$("#bill_zipcode").val($(this).find('option:selected').attr('data-zipcode'));
$("#bill_country").val($(this).find('option:selected').attr('data-country'));
})
});

Categories