Add selected select option to jquery form submit - javascript

Just having a little trouble with part of my code.
Basically new elements are added into the page through .html() and ajax response. An example of added elements are commented in the code. Because the codes were added into the page through .html the form wasn't submitting the added fields. So I used .append($('.newfields') which works perfectly on the checkbox but fails on the select box which is the purpose of this question.
Any way to include the new select boxes on form submit?
Thank you all in advance for you help!
$('.button').click(function(){
$('#domaincheckform').append($('.newfields'));
$( "#domaincheckform" ).submit();
});
<form action="cart.php" id="domaincheckform" method="post">
<select form="domaincheckform" name="termselect[]">
<option value="1">1 year</option>
<option value="2">2 year</option>
</select>
<input type="checkbox" name="did[]" value="example1">
<!--EXAMPLE ADDED FIELD-->
<select form="domaincheckform" class="newfields" name="termselect[]">
<option value="1">1 year</option>
<option value="2">2 year</option>
</select>
<input type="checkbox" class="newfields" name="did[]" value="example2">
<!--END OF EXAMPLE ADDED FIELD-->
<span class="button">Button</span>
</form>

You need to wrap your select inside a div
try this
<form action="cart.php" id="domaincheckform" method="post">
<select form="domaincheckform" name="termselect[]">
<option value="1">1 year</option>
<option value="2">2 year</option>
</select>
<input type="checkbox" name="did[]" value="example1">
<!--EXAMPLE ADDED FIELD-->
<div class="append_content"><select form="domaincheckform" class="newfields" name="termselect[]">
<option value="1">1 year</option>
<option value="2">2 year</option>
</select> </div>
<input type="checkbox" class="newfields" name="did[]" value="example2">
<!--END OF EXAMPLE ADDED FIELD-->
<span class="button">Button</span>
</form>
Also make changes in your js like this
<script>
$(document).ready(function() {
$('.button').click(function(){
$('#domaincheckform').append($('.append_content').html());
$( "#domaincheckform" ).submit();
});
});
</script>
now the select is inside a div append_content its easy to fetch its content as select has multiple html content so it will return object if you use only selector name $(".newfields")

$(selector).click(function(){}) sometimes fails to work. Try using $(selector).on("click", function(){})
It worked here: https://jsbin.com/vemuxukehi/edit?html,js,output

Heres is a simple working example that adds the and displays it in the submitted form data
https://jsfiddle.net/uapejgu5/
$(function () {
$("#submit").click(function () {
$("#result").html($('#myform').serialize())
return false
})
$("#add").click(function () {
var select = $("<select>", {
name: "newSelect"
})
$(select).append($("<option>", {
text: "myNewOption",
value: "myNewValue"
}))
$("#myform").append(select)
})
})

Check out this fiddle:
https://jsfiddle.net/bbdkr9g5/1/
Basically what you wrote, plus some code to print out the form result in the console. And you had the same name attributes on both your static and your dynamically-inserted elements, which is probably not what you wanted.

You should clone the elements and remove the newfields class before adding them to the form.
$('.button').click(function(){
$('#domaincheckform').append($('.newfields').clone().removeClass('newfields'));
$('#domaincheckform').submit();
});
Here is a JSFiddle example that skips the actual submit: JSFiddle

Related

How to show input and remove it based on select box?

I have two input I need to show one of them based on the select box:
html code:
<select id="type-price">
<option value="">Choose one...</option>
<option value="numeric">Numeric </option>
<option value="percentage">Percentage</option>
</select>
<div id="input_type1">
<input type="text" name="Numeric">
</div>
<div id="input_type2">
<input type="text" name="Percentage">
</div>
jQuery code:
$('#type-price').on('change',function(){
if($(this).val()=== "numeric"){
$("#input_type1").show();
$("#input_type2").hide();
}else if ($(this).val()=== "percentage"){
$("#input_type1").hide();
$("#input_type2").show();
}
});
Now it's totally fine like that but my issue I have php request when I show input_type1 then hide input_type2 the request pick up second one which is null so I need to delete the hide one at all form Dom tree!
You can empty the div which contain the input and you will have only one input in your DOM. On each change of select, it will fill the concerne div by the input html.
Also you'd used wrong selector, the # selector is for id and you have used an class in your HTML code.
The JQuery class selector is ..
function removeAll() {
$("#input_type1").html('');
$("#input_type2").html('');
}
removeAll();
$('#type-price').on('change',function(){
removeAll();
if ($(this).val() === "numeric"){
$("#input_type1").append('<input type="text" value="numeric">');
} else if ($(this).val() === "percentage"){
$("#input_type2").append('<input type="text" value="percentage">');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="type-price">
<option value="" disabled selected>Choose one...</option>
<option value="numeric">Numeric </option>
<option value="percentage">Percentage</option>
</select>
<div id="input_type1">
<input type="text" value="numeric">
</div>
<div id="input_type2">
<input type="text" value="percentage">
</div>
Here is an example with one field.
$(function() {
$("#type-price").change(function(e) {
$(".input-type").fadeIn("slow").find("input").attr("name", $(this).val().toLowerCase());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="type-price">
<option value="">Choose one...</option>
<option value="numeric">Numeric </option>
<option value="percentage">Percentage</option>
</select>
<div class="input-type" style="display: none;">
<input type="text">
</div>
Besides some syntax problem in your jQuery class selector, Thinking about performance, It's simply better to prevent the (non-visible) input from being sent.
Shorter coding and less dom manipulation.
$('#type-price').on('change',function(){
$('.input_type1').toggle($(this).val()=="numeric");
$('.input_type2').toggle($(this).val()=="percentage");
});
//To prevent the non-visible from being posted
//Eithr we check the form using submit handler or the button and prevent the
//from being sent do our stuff then send it...
$('#myForm').submit(function() {
$('input:hidden').attr('name', '');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<select id="type-price">
<option value="">Choose one...</option>
<option value="numeric">Numeric </option>
<option value="percentage">Percentage</option>
</select>
<div class="input_type1">
<input name="inp1" type="text" placeholder="1">
</div>
<div class="input_type2">
<input name="inp2" type="text" placeholder="2">
</div>
<input type="submit" value="Send">
</form>

Change visibility of forms depending on chosen option

I'm making a research form which will display differently depending on the choice of a SELECT value. I have applied some jQuery tricks after searching through here. Unfortunately, it doesn't work at all. Here is my code:
HTML:
<select name="options" id="choice">
<option value="0" selected="true">Choose...</option>
<optgroup label='ABC'>
<option value="1">...DEF</option>
<option value="2">...GHL</option>
</optgroup>
<optgroup label="MNP:">
<option value="3">X</option>
<option value="4">Y</option>
<option value="5">Z</option>
</optgroup>
</select>
<form id="opt1" name="opt1" style="display: none">11111111</form>
<form id="opt2" name="opt2" style="display: none">22222222</form>
<form id="opt3" name="opt3" style="display: none">33333333</form>
<form id="opt4" name="opt4" style="display: none">44444444</form>
<form id="opt5" name="opt5" style="display: none">55555555</form>
JavaScript:
$("#choice").change(function() {
$("form").hide();
$("#opt" + $(this).val()).show();
});
Try this one
$(document).ready(function(){
$('select').change(function() {
//var selected = $(':selected', this);
//alert(selected.closest('optgroup').attr('label'));
$("form").hide();
$("#opt" + $(this).val()).show();
});
});
DEMO here
A #guradio suggests, the code works fine in fiddle. To debug the issue try putting alerts or console.log() to know that the issue it. Hope you have the jQuery library added to your page.
Try these:
$("#choice").change(function() {
alert('fine till here');
$("form").hide();
$("#opt" + $(this).val()).show();
});
Your code is working,I think you are missing j query library on form. please add.
see jsfiddle.net/f5xuc0gh/

Select first option that is not empty

Does anyone know how to autoselect in a selectbox? I want to do is even though there is a blank option the selectbox will still show the option that has a value on it.
Does anyone know how to do it in jquery?
html code:
<select name="name">
<option></option>
<option>Mark</option>
</select>
<select name="age">
<option></option>
<option>16</option>
</select>
May this help you :
HTML:
<select name="name">
<option></option>
<option>Mark</option>
</select>
<select name="age" id='some'>
<option></option>
<option>16</option>
</select>
Jquery:
$($('#some').children()[1]).attr('selected',true)
If you have more than one empty option, and there is no order, this is the best solution I think: jsFiddle Live Demo
What we've done here is, checking every selectbox by a each loop:
$('select').each(function()
{
});
And then inside the loop we find the first option which is not empty:
$(this).find('option:not(:empty)').first()
And make it selected by prop:
$(this).find('option:not(:empty)').first().prop('selected',true);
So the whole jQuery and Html will be:
jQuery
$('select').each(function()
{
$(this).find('option:not(:empty)').first().prop('selected',true);
});
HTML
<select name="name">
<option></option>
<option>Mark</option>
</select>
<select name="age">
<option></option>
<option>16</option>
<option>20</option>
<option></option>
<option>55</option>
<option></option>
</select>
If you want to do this to all select boxes on the page, use this:
$(function () {
$('select').each(function () {
$(this).find('option').not(':empty()').first().attr('selected', true);
})
});
It grabs each select, finds the first option that is not empty (read: has text inside it) and sets the selected attribute.
See the fiddle.
No need for javascript to do this, if you want to select (Mark) for example, do it like this
<select name="name">
<option></option>
<option selected>Mark</option>
</select>
and in XHTML:
<select name="name">
<option></option>
<option selected="selected">Mark</option>
</select>

jQuery input not hidden

I'm working on a new website based on CodeIgniter. I'm trying to hide some elements to my form depending on an input value, but the field doesn't hide but stays disabled.
Here's the code I have :
HTML :
<div class="clearfix">
<label for="form-timezone" class="form-label">Filters<small>Options</small></label>
<div class="form-input">
<?php
echo form_dropdown('filter', $filters,'', 'id="form-timezone"');
echo form_dropdown('city', $cities, '', 'id="city"');
echo form_dropdown('country', $countries, '', 'id="country"');
?>
</div>
</div>
Which basically gives something like :
<div class="clearfix">
<div class="form-input">
<select name="filter" id="form-timezone">
<option value="city">City</option>
<option value="country">Country</option>
</select>
<select name="cities" id="city">
<option value="Paris">Paris</option>
<option value="London">London</option>
</select>
<select name="countries" id="country">
<option value="fr">France</option>
<option value="en">England</option>
</select>
</div>
</div>
JS :
$(function() {
$("#city").hide();
$("#country").hide();
$("#form-timezone").change(function() {
if ( $("#form-timezone").val() == "city"){
$("#city").show();
$("#country").hide();
}
else if ( $("#form-timezone").val() == "country"){
$("#city").hide();
$("#country").show();
}
});
});
I tried to add an <input> field to my html, and to hide it in the js, and it worked well. I don't know why, but it seems that only the form_dropdown doesn't hide...
Do someone has an idea of what I'm doing wrong please ?
Thanks.
I don't know what you mean by not working. But your code can be a lot simpler with no if statements.
$("#form-timezone").change(function() {
var el = $('#' + $(this).val()); // <-- store matched element
el.show(); // <-- show matched element
$("#country,#city").not(el).hide(); // <-- hide unmatched element
});
And they work fine in this fiddle (they hide and not disable) - tested in Firefox/Chrome/IE9
http://jsfiddle.net/5LNWr/1/
It works for me in this fiddle.
The Javascript code you posted was missing a closing }); after the DOM ready handler. I've assumed the output is a <select> element for each PHP echo statement.
You mention that the form field "stays disabled." Does this mean they're disabled to begin with? Disabled form elements don't capture events in all browsers (Firefox).
If that isn't the case, can you provide a jsfiddle?
<div class="clearfix">
<div class="form-input">
<select name="filter" id="form-timezone">
<option value="city">City</option>
<option value="country">Country</option>
</select>
<!-- Here a select foreach city and country -->
</div>
</div>
See how there is no id's for City and Country? You cannot select on ID's here.
$("#city").show();
$("#country").hide();
Won't work. Maybe try
var $firstOption= $(“#form-timezone option:first”)

jQuery: Show/Hide Elements based on Selected Option from Dropdown

UPDATE: The original question asked was answered. However, the code revealed for all. So, I've modified my question below:
So I have the following dynamically generated html via php
<div class="image-link link-posttypes mainSelector1">
<select id="wp_accordion_images[20110630022615][post_type]" name="wp_accordion_images[20110630022615][post_type]">
<option value="">default</option>
<option value="post" class="post-type">Post</option><option value="page" class="post-type">Page</option><option value="dp_menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option><option value="custom-link">Custom Link</option>
</select>
</div>
<div class="image-link link-pages1">
<select id="wp_accordion_images[20110630022615][page_id]" name="wp_accordion_images[20110630022615][page_id]">
<option value="50" class="level-0">About</option>
<option value="65" class="level-0">Contact</option>
<option value="2" class="level-0">Sample Page</option>
<option value="60" class="level-0">Staff</option>
</select>
</div>
<div class="image-link link-posts1">
<select onchange="javascript:dropdown_post_js(this)" id="wp_accordion_images[20110630022615][post_id]" name="wp_accordion_images[20110630022615][post_id]">
<option value="http://localhost/tomatopie/?p=1" class="level-0">Hello world!</option>
</select>
</div>
<div class="image-link link-custom1">
<input type="text" size="25" value="" name="wp_accordion_images[20110630022615][image_links_to]">
</div>
***THEN IT REPEATS four times: where the #1 goes to 2..3...4 (max to 4 at this time).
I have the ability to label div .classes, select #ids, and option classes. However, what I want to be able to do is based on the option selected from div .link-posttypes, I want to reveal .link-pages (if page is selected) or .link-posts (if post is selected) and .link-custom for all others (except the default).
So as written on the screen there should only be the initial div, and once the user selects an item, the appropriate div appears.
I have never developed anything in jQuery or javascript. This is my maiden voyage. Any help will be greatly appreciated!
***Also, this will be loaded via an external js file.
Here is the final answer that worked:
jQuery(document).ready(function($) {
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").slideDown('slow');
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal=="page"){
$(this).parent().nextAll(".link-pages").slideDown('slow');
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}else if(selectedVal!=""){
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().next().nextAll(".link-custom").slideDown('slow');
}else{
$(this).parent().nextAll(".link-pages").hide();
$(this).parent().nextAll(".link-posts").hide();
$(this).parent().nextAll(".link-custom").hide();
}
});
});
jQuery(document).ready(function($) {
$(".image-content select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="content-limit"){
$(this).parent().next().nextAll(".content-limit-chars").slideDown('slow');
$(this).parent().nextAll(".content-custom").hide();
}else if(selectedVal=="custom-content"){
$(this).parent().nextAll(".content-limit-chars").hide();
$(this).parent().next().nextAll(".content-custom").slideDown('slow');
}
});
});
Thanks for your help!
Assuming that you're outputting proper IDs, you can do something like this (note I replaced the id):
$(window).load(function(){
// hide all the divs except the posttypes
$('.image-link').not('.link-posttypes').hide();
$('#wp_accordion_images_20110630022615_post_type').change(function() {
var divSelector = '.link-' + $(this).val();
$('.image-link').not('.link-posttypes').hide();
$(divSelector).show();
});
});
Also, consider changing your options like this:
<option value="posts" class="post-type">Post</option>
<option value="pages" class="post-type">Page</option>
<option value="menu_items" class="post-type">Menu Items</option>
<option value="wps_employees" class="post-type">Employees</option>
<option value="custom">Custom Link</option>
Here's a jsfiddle for this: http://jsfiddle.net/JrPeR/
There's my understandable jquery script
jQuery(document).ready(function($) {
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
$(".link-posttypes select").change(function(){
var selectedVal = $(":selected",this).val();
if(selectedVal=="post"){
$(".link-pages").hide();
$(".link-posts").show();
$(".link-custom").hide();
}else if(selectedVal=="page"){
$(".link-pages").show();
$(".link-posts").hide();
$(".link-custom").hide();
}else if(selectedVal!=""){
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").show();
}else{
$(".link-pages").hide();
$(".link-posts").hide();
$(".link-custom").hide();
}
});
});
Demo here. Take me couple minute to make you easy to understand. Have fun.
http://jsfiddle.net/JrPeR/3/
added a conditional so if its not the two variables it defaults to the custom.

Categories