I have forms similar to this:
<form class="submission-form" method="POST" action="/post/create/">
<input type="text" name="title">
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="button" value="Publish">
</form>
The various fields in the form are not known beforehand and can change; what is known is the fact that every form that needs processing has a submission-form class on it, and it contains a button with the class submit-button.
I'm trying to add an event listener on the input.submit-button that will traverse on the form its contained in, find all the fields, and create an object from it. For example, in the above case, the object created might look like:
{
title: "My first post",
post_content: "Hello there!",
visibility: 1
}
How should I go about doing this?
Iterate through input, textarea and select elements and create an object with properties from element name and value:
$('.submit-button').on('click', function() {
var o = {};
$(this).closest('form')
.find('input, textarea, select')
.not(':button')
.each(function() {
o[$(this).attr('name')] = $(this).val()
});
console.log(o);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="submission-form" method="POST" action="/post/create/">
<input type="text" name="title" />
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="button" value="Publish" />
</form>
References
.closest()
.not()
.each
You could use serializeArray() and then use reduce() on that array to return desired object.
$("form").submit(function(event) {
var data = $(this).serializeArray().reduce(function(r, e) {
r[e.name] = e.value;
return r;
}, {})
console.log(data)
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="submission-form">
<input type="text" name="title">
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="submit" value="Publish">
</form>
Use serializeArray() to create and array of objects for name value pairs and loop through them to create a single object.
$('form').submit(function(e){
e.preventDefault();
var obj = $(this).serializeArray()
var final= {};
$.each(obj, function(index,object){
final[object.name] = object.value;
});
console.log(final);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="submission-form" method="POST" action="/post/create/">
<input type="text" name="title">
<textarea name="post_content"></textarea>
<select name="visibility" class="form-control">
<option value="1">Public</option>
<option value="2">Private</option>
</select>
<input class="submit-button" type="submit" value="Publish">
</form>
Related
I am trying to add a search feature based on a text input and a drop-down.
So I am trying to make it work with the following form fields:
Text input {text_1}
Drop-down (2 options)
Submit button
If first option is selected in the drop-down the form should be submitted to https://url1/?={text_1}, if second option is selected it should be submitted to https://url2/?={text_1}.
I have written so far:
<form>
<input type="text" id="text_1" name="text_1" value="test" data-alias="" class="form-control">
<select id="selectlist_1" name="selectlist_1" data-alias="" class="form-control">
<option value="option_1" >Option_1</option>
<option value="option_2" >Option_2</option>
</select>
<button type="submit" id="button_1" name="button_1" class="btn btn-primary" >Submit</button>
</form>
Otherwise, there is also this example: https://hii.com/careers/
I give you an example:
<script>
function go(v){
if (v.url.value===1){
v.action="http://www.google.com"
}else {
v.action="http://www.apple.com"
}
}
</script>
<form onsubmit="go(this)">
<input type="text" name="text_1" value="txt">
<select name="url">
<option value="1">Google</option>
<option value="2">Apple</option>
</select>
<input type="submit" value="submit">
</form>
Augment a simple form with the controls you want, with a script that sets up a behaviour where the form's action attribute value changes with the selection in the drop-down control:
<form>
<input name="foobar" />
<select name="fruit">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
</select>
<script>
(script => {
const fruit_control = script.closest("form").elements.fruit;
fruit_control.addEventListener("change", ev => {
ev.target.form.action = ({
"apples": "https://url_1",
"oranges": "https://url_2"
})[ev.target.value];
});
})(document.currentScript);
</script>
</form>
The value of the text input control will be sent with the query string, i.e. as ?foobar=... at the end of the URL, as the form is submitted, to the URL that's correspondent with the option selected in the drop-down.
Whether you have a submit button at the end of the form, or not, makes no difference to the behaviour of the form because a form may be submitted even without a submit button.
I found a working solution after doing some searches.
Here is solution in case anyone need it.
jQuery('#search_page_form').submit(function() {
// get all the inputs into an array.
var stext = jQuery('#search_page_form #looking-for').val();
var cars = jQuery('#search_page_form #cars').val();
var url = '';
if(cars == 'nns'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext;
}else if(cars == 'mt'){
var url = 'https://tsd-careers.hii.com/en-US/search?keywords='+stext;
}else if(cars == 'is'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext+'&locationsearch=Pascagoula%2C+MS&geolocation=';
}else if(cars == 'ch'){
var url = 'https://careers.huntingtoningalls.com/search/?searchby=location&createNewAlert=false&q='+stext+'&locationsearch=Newport+News%2C+VA&geolocation=';
}
if(url != ''){
window.open(url, '_blank');
}else{
alert('Please select Division');
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search_page_form" onsubmit="return false;">
<div class="form-group">
<label for="looking-for">What are you looking for ?</label>
<input type="text" id="looking-for" name="looking-for" class="form-control" placeholder="Enter keywords....">
</div>
<div class="form-group">
<select id="cars" name="cars" class="form-control nice-select">
<option selected="" value="">Division</option>
<option value="nns">NEWPORT NEWS SHIPBUILDING</option>
<option value="mt">MISSION TECHNOLOGIES</option>
<option value="is">INGALLS SHIPBUILDING</option>
<option value="ch">CORPORATE HEADQUARTERS</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="SEARCH" class="btn white-btn search_btn">
</div>
</form>
I need help. I have this form:
<form name="user_cause" method="post">
<div class="form-group">
<select id="subject" required="required" class="form-control" onchange="showHide()">
<option value="subject">Subject</option>
<option value="test_1">Test_1</option>
<option value="test_2">Test_2</option>
</select>
</div>
<div class="form-group">
<textarea id="subject_message" required="required"
class="form-control" rows="5" disabled>
</textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
I wish I could change the text in the disabled textarea according to the choice. how to do it with javascript?
var ourArea = document.getElementById('subject_message');
var selectSubject = document.getElementById('subject');
ourArea.textContent = selectSubject.value; // omit this if you don't want initial value to be reflected in the text area
function showHide(){
ourArea.textContent = selectSubject.value;
}
Using jQuery, $("#subject").change(function(e) { $("#subject_message").val($(this).val())});
A jQuery way:
$("#subject").change (function() {
$("#subject_message").text($("#subject option:selected").text();
});
Hi I have form which contains three search criteria.
These search criteria are jobs, resume, recruitment consultant.
Based on the drop down, fields are updated accordingly.
Based on the select value I want to change the action on the form, and name of the submit button. Problem is putting values with hyphen in option select makes jquery not work.
<form method="get" name="search" action="search-job-results?">
<select class="homepage4" name="search_for" id="search_for">
<option value="Jobs">Jobs</option>
<option value="Resume">Resumes</option>
<option value="Recruitment Consultant">Recruitment Consultants</option>
</select>
<input type="submit" name="searchjobbutton" id="search_submit" value="Submit">
</form>
Change the form action as per following
action="search-recruitment-consultant-results?"
action="search-resume-results?"
action="search-job-results?"
And the button name (NOT VALUE OR TEXT) as per following
name="searchrecruitmentconsultantbutton"
name="searchresumebutton"
name="searchjobbutton"
I put these in option values accordingly
search-recruitment-consultant-results?
search-resume-results?
search-job-results?
and then used
<select name="search_for" onchange="this.form.action=this.value;">
but putting hyphen in option values makes the jquery show/hide not work
Try this code, see i have use hyphen in option and it works properly.
<form method="get" name="search" id="form" action="search-job-results?">
<select class="homepage4" name="search_for" id="search_for">
<option value="Jobs">Jobs</option>
<option value="Resume">Resumes</option>
<option value="Recruitment-Consultant">Recruitment Consultants</option>
</form>
<script>
$(document).ready(function() {
$("#search_for").change(function(){
if($(this).val()=='Jobs')
{
$("#form").attr("action",'search-job-results?');
$("#search_submit").attr('name',"searchjobbutton");
}
else if($(this).val()=='Resume'){
$("#form").attr("action",'search-resume-results?');
$("#search_submit").attr('name',"searchresumebutton");
}
else if($(this).val()=='Recruitment-Consultant'){
$("#form").attr("action",'search-recruitment-consultant-results?');
$("#search_submit").attr('name',"searchrecruitmentconsultantbutton");
}
});
});
</script>
i think this will help you
add id for your form 'formId'
$(document).ready(function(){
$('#search_for').change(function(){
var cur = $(this);
var search = cur.val();
if(search == 'job'){
$('#formId').attr('action', 'search-job-results?');
$("search_submit").attr('name', 'searchjobbutton');
} else if(search == 'Resume'){
$('#formId').attr('action', 'search-resume-results?');
$("search_submit").attr('name', 'searchresumebutton');
}else if(search == 'Recruitment Consultant'){
$('#formId').attr('action', 'search-recruitment-consultant-results?');
$("search_submit").attr('name', 'searchrecruitmentconsultantbutton');
}
});
});
try this
Add data attribute with button name
only you need to add - onchange="$(this).parent().attr('action', $(this).val()); $('#search_submit').val($(this).find(':selected').data('name'));" in the select
and data-name="" in the option
<form method="get" name="search" action="search-job-results?">
<select class="homepage4" name="search_for" id="search_for" onchange="$(this).parent().attr('action', $(this).val()); $('#search_submit').val($(this).find(':selected').data('name'));">
<option value="search-job-results?" data-name="searchjobbutton">Jobs</option>
<option value="search-resume-results?" data-name="searchresumebutton">Resumes</option>
<option value="search-recruitment-consultant-results?" data-name="searchrecruitmentconsultantbutton">Recruitment Consultants</option>
</select>
<input type="submit" name="searchjobbutton" id="search_submit" value="Submit">
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script>
<form method="get" name="search" action="search-job-results?">
<select class="homepage4" name="search_for" id="search_for" onchange="$(this).parent().attr('action', $(this).val()); $('#search_submit').val($(this).find(':selected').data('name'));">
<option value="search-job-results?" data-name="searchjobbutton">Jobs</option>
<option value="search-resume-results?" data-name="searchresumebutton">Resumes</option>
<option value="search-recruitment-consultant-results?" data-name="searchrecruitmentconsultantbutton">Recruitment Consultants</option>
</select>
<input type="submit" name="searchjobbutton" id="search_submit" value="Submit">
</form>
Instead of writing multiple forms, just write one and use .change() and data-* attribute which is used to create custom tags. Store the button names inside <option data-name="button name"> then you can access this value with on change.
The data-* attributes is used to store custom data private to the page or application.
.change()
Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
$('#search_for').on('change', function () {
$('form[name="search"]').attr('action', $(this).val()).find(':submit').attr('name', $(this).find(':selected').data('name'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get" name="search" action="search-job-results?">
<select class="homepage4" name="search_for" id="search_for">
<option data-name="searchjobbutton" value="search-job-results?">Jobs</option>
<option data-name="searchresumebutton" value="search-resume-results?">Resumes</option>
<option data-name="searchrecruitmentconsultantbutton" value="search-recruitment-consultant-results?">Recruitment Consultants</option>
</select>
<input type="submit" name="searchjobbutton" id="search_submit" value="Submit">
</form>
I'm trying to add <input name="input"> values to <select> <options> each time when I change the value with onblur function.
In this case it does change the value of <input name="output"> but I would like to add them multiple, so that's why I'm looking for adding values in to select options.
Is this possible?
Thanks.
function add(form) {
form.output.value = form.input.value;
}
<form>
<input name="input" type="text" value="" onblur="add(this.form);">
<input tabindex="-1" name="output" type="text" value="">
<select multiple>
<option>Test</option>
</select>
</form>
if you mean that after changing input value , add it's value as option to select , yea it's possible
I've wrote the code see the demo at below link
https://jsfiddle.net/oxxqw71s/
and code :
$("select").append($('<option>', {value:v, text:v}));
You can implement like below.
function add(val){
var data = val.input.value;
val.output.value = data;
var option = document.createElement("option");
option.text = data;
val.opt.add(option, val.opt[0]);
}
<form>
<input name="input" type="text" value="" onblur="add(this.form);">
<input tabindex="-1" name="output" type="text" value="">
<select multiple name="opt">
<option>Test</option>
</select>
</form>
HTML
<form>
<input name="input" type="text" value="" onblur="add(this.form);">
<input tabindex="-1" name="output" type="text" value="">
<select multiple name="opt">
<option>Test</option>
</select>
</form>
JS
function add(val){
var data = val.input.value;
val.output.value = data;
var option = document.createElement("option");
option.text = data;
val.opt.add(option, val.opt[0]);
}
On button click i want to fetch selected value of multiple select boxes. i can able to fetch value from array of textboxes but im not able to get select box value. it returns empty array.
$("#add_user_button").click(function(){
var username=[];
$("input[name=username]").each(function(){
username.push($(this).val());
});
var usertype=[];
$("input[name=usertype]").each(function(){
usertype.push($(this).val());
});
var ajaxdata={"UserName":username,"UserType":usertype};
console.log(JSON.stringify(ajaxdata));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="user_group">
<input type="text" id="user_username" placeholder="User Name" name="username">
<select id="user_usertype" name="usertype">
<option value="1">Admin</option>
<option value="2">Normal</option>
</select>
</div>
<div class="clone_user_input"><div id="user_group_1">
<div class="form-group">
<input type="text" id="user_username" placeholder="User Name" name="username">
<select id="user_usertype" name="usertype">
<option value="1">Admin</option>
<option value="2">Normal</option>
</select>
</div>
</div>
<button id="add_user_button">Add User</button>
Select is not input. Use:
var usertype=[];
$("select[name=usertype]").each(function(){
usertype.push($(this).val());
});
Also note that you have duplicate IDs for elements. IDs should be always unique. You can rather use same class names as an alternative to this.