Select value of current form in JQuery - javascript

I have many forms on my site. When the Submit is triggered on the form I expect to receive an id of the form and the option selected.
html
<form name="order">
<select id="count">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br/>
<input type="text" name="id" value="6" />
<input href="#" type="submit" value="Submit" />
</form>
JavaScript
var fancyboxOptions = {
ajax : {
type: "POST",
data: {
id: null,
count: null
}
}
}
$(document).ready(function() {
fancyboxOptions.ajax.data.id = $('input[name="id"]').val();
fancyboxOptions.ajax.data.count = $('#count').val();
$('div#buy input').fancybox(fancyboxOptions);
$('#count').change(function() {
fancyboxOptions.ajax.data.count = $('#count').val();
});
With this code I receive only data from the first form -- when the submit is triggered other forms I receive data from the first form rather than from the form I pressed submit on.
How do I restructure my code, so the form submits triggers the submit to give me only the the data in the form for which I pressed submit.
PS Do not pay attention a fancybox, it's work good.

May want to change your code to something like this
<script>
$('input[name=id]').parent().change(function(){
fancyboxOptions.ajax.data.id = $(this).find('input[name="id"]').val();
fancyboxOptions.ajax.data.count = $(this).find('#count').val();
});
</script>
This will install a change handler on each form which contain a input field named id, and the callback function (which is installed on the parent() form ) will have access to "this" which the can navigate the DOM and find all the sub-fields relative to the form node.

Do you need to loop through all the forms on your page and get their values after clicking one button? If so, try this:
$('form').each(function(){
var currentForm = $(this);
var someValue = currentForm.find('input[name="id"]').val();
// do the rest here
});
If that's not your question, then maybe it has something to do with using ids for your inputs instead of classes. You can only use an id once, so if your other forms also include < select id="count"> then when jQuery reads that value, it will only ever return the value of the first one.
Hope this helps...

Related

Keep the value on dropdown list after submitting form

How do I display the selected option on drop down list after submitting form? It always displays the first option.
<form id="myform" >
<label for="selectoption">Birimler</label>
<select id="SelectOption" name="SelectOption" onchange="$('#myform').submit();" value="a">
<option>Seçiniz</option>
<option id="aYo" value="Yonetim">Yönetim</option>
<option id="aAr" value="Arge">ARGE</option>
<option id="aDe" value="Depo">Depo/Sevkiyat</option>
<option id="aIK" value="IKID">İnsan Kaynakları/İdari İşler</option>
</select>
</form>
Try this:
<script type="text/javascript">
function getOption() {
selectElement = document.querySelector('#selectoption');
output = selectElement.value;
document.querySelector('.output').textContent = output;
}
</script>
or try this:
selectElement.options[selectElement.selectedIndex].value
selectedIndex---It is used to set or get the index of the selected element in the collection.
length---It is read-only property that is used to get the number of elements in the collection.
You can save the value in localStorage like:
localStorage.setItem('selectOption', $(#SelectOption).val());
then your browser will remember this value even after page reload (form send), then you can fill your form by getting the value
$(#SelectOption).val(localStorage.getItem('selectOption'))
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
For example, this can be useful when:
Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL
Kindly check this link.
try this
$(document).ready(function(){
$('#SelectOption').change(function (e) {
console.log($( "#SelectOption" ).val())
let SelectOptionValue = $( "#SelectOption" ).val()
console.log("click",SelectOptionValue)
// $('#myform').submit();
$( "#SelectOption" ).val("Depo")
console.log($( "#SelectOption" ).val())
console.log("click")
e.preventDefault();
});
});
used viewbag
<select style="width:100px" id="SelectOption" name="SelectOption" value="a">
<option>#Html.Label("-",(string)ViewBag.Name,new {#class = "mylabel" })</option>

jQuery change selected value and submit form basd of localStorage value

I have a problem. I have select with name category and have code:
if (localStorage.getItem('category') !== null) {
$('select[name=category]').val(localStorage.getItem('category')).trigger('change');
$('.form-search').submit();
}
If in Local storage I have id, then I change selected value in select. But How I can submit this form? My code is not working, because page reloading many times..
MY form:
<form method="get" class="form-search">
....
<select name="category">
<option value="1">Auto</option>
<option value="2">Sport</option>
...
</select>
</form>
Because the form hasn't action, browser submit form to this page and page reloaded and because you don't removed localStorage the code runned again. So you should remove localStorage category before submitting form.
var category = localStorage.getItem('category');
if (category !== null) {
$('select[name=category]').val(category).trigger('change');
localStorage.removeItem('category');
$('.form-search').submit();
}
You may not need the trigger
if(localStorage.getItem('category') !== null) {
$('select[name=category]').val(localStorage.getItem('category'));
$('.form-search').submit(function(e){
e.preventDefault();
});
}
Check code here

Jquery - setting value of <input> - function is called, but values not set

I'm trying to use jquery to set the value of some tags. This is for a the admin side of a wordpress widget which will store a list of records, keyed by a date that are retrieved by using a <select>. In order to achieve this I'm having to to some janky value storage in data-* attributes to link the contents of three hidden <select> lists.
The idea is that the hidden list's values are retrieved by grabbing the visible <select>'s selected <option>'s data-date attribute value and grabbing the <option> in each hidden <select> that has a matching data-date. These values are then put into <input> fields for the user to edit.
HTML fragment
<label for="spdates">Special Dates:</label>
<p>
<select id="spdates">
<option data-date='new' value='new'>New Date</option>
<option data-date='23/05/1992' value='23/05/1992'> 23/05/1992-jake</option>
<option data-date='15/08/1997' value='15/08/1997'> 15/08/1997-rebecca</option>
<option data-date='17/03/1995' value='17/03/1995'> 17/03/1995-clive</option>
</select>
</p>
<p>
<label for="spname">Special Name:</label>
<input class="widefat namspani" id="spname" type="text" value="" />
</p>
<p>
<label for="sptext">Special Text:</label>
<input class="widefat namspani" id="sptext" type="text" value="" />
</p>
<p>
<label for="spdate">Special Date(dd/mm/yyyy):</label>
<input class="widefat namspani" id="spdate" type="date" value="" />
</p>
<p>
<label for="spimage">Special Image:</label>
<br />
<input type="text" class="img anisp" id="spimage" value="" />
<input type="button" class="select-imgsp" value="Select Image" />
</p>
<select id="eventNames" name='widget-dates_widget[__i__][eventNames][]' multiple hidden>
<option data-date='23/05/1992' value='[23/05/1992]jake' selected> jake</option>
<option data-date='15/08/1997' value='[15/08/1997]rebecca' selected> rebecca</option>
<option data-date='17/03/1995' value='[17/03/1995]clive' selected> clive</option>
</select>
<select id="eventText" name='widget-dates_widget[__i__][eventText][]' multiple hidden>
<option data-date='23/05/1992' value='[23/05/1992]yay me' selected> yay me</option>
<option data-date='15/08/1997' value='[15/08/1997]rebecca' selected> rebecca</option>
<option data-date='17/03/1995' value='[17/03/1995]clive' selected> clive</option>
</select>
<select id="eventImages" name='widget-dates_widget[__i__][eventImages][]' multiple hidden>
</select>
Jquery function
$(function() {
//onchange for the date select to populate the other boxes
$(document).on('change', 'select#spdates', function(evt) {
var date = $(this).find(":selected").attr("data-date");
if (date == "new") {
//new date selected, discard what's in the boxes and blank values
$(".namspani").val("");
} else {
//different date selected, discard what's in the boxes and blank values
alert($("#eventNames").find("[data-date='" + date + "']").text());
$("#spname").val($("#eventNames").find("[data-date='" + date + "']").text()); //grab from other lists
$("#sptext").val($("#eventText").find("[data-date='" + date + "']").text());
$("#spdate").val(date);
$("#spimage").val($("#eventImagess").find("[data-date='" + date + "']").text());
}
});
})
I've confirmed my code is being run as I've put an alert() containing one of the values I'm trying to set in the branch of the function i expect to run. In practice the alert files, with the right content, however the input fields don't fill with data.
This code works in jsfiddle https://jsfiddle.net/ForceGaia/j363mv3w/1/ but not natively in firefox or chrome.
What is going on? I'm fairly new to jquery, so I'm now wondering if I'm missing something basic.
EDIT:
The alert fires, so i know it's getting to the right chunk of code, thus some version of JQuery seems to be working. console.log($().jquery); puts 1.12.4 to the log.
I tried putting hardcoded strings into the .var() parameters, still nothing.
I moved the $("#spname") search into a variable to see if it was finding it.
var spnamedom = $("#spname");
After that chunk of code spnamedom was an array of elements (which, knowing jQuery, i expected) I tried accessing the 0th element and it was the correct element.
so i tried both of the following
var spnamedom = $("#spname");
spnamedom.val("a thing");
And
var spnamedom = $("#spname")[0];
spnamedom.val("a thing");
spnamedom is always what I'm expecting, but neither work. There is an element with the correct id in both cases, either as the 0th element, or straight in the variable.
he latter puts TypeError: spnamedom.val is not a function to the log. I assume that error is because I'm no longer in a JQuery object and am looking at a DOM object after i grabbed the 0th element. I could possibly edit this raw DOM element to get what I want, but the initial question remains, why does my code work in jsfiddle, but not a live browser; as from the reading I'm doing, this should work.
I have also found jQuery .val change doesn't change input value and using `.attr('value','text') doesn't work either.
EDIT 2
I realised that in my code i have something that does what i want already on different controls, and it works - which is even more bewildering. I had totally forgotten that the code was performing the same action when it came down to it.
Before i only supplied an exerpt of my JQuery script, here's the entire thing
var image_field;
jQuery(function($) {
$(document).on('click', 'input.select-img1', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
$(document).on('click', 'input.select-img2', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
$(document).on('click', 'input.select-img3', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
$(document).on('click', 'input.select-imgsp', function (evt) {
image_field = $(this).siblings('.img');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function (html) {
imgurl = $('img', html).attr('src');
image_field.val(imgurl);
tb_remove();
}
// onchange for the date select to populate the other boxes
$(document).on('change', 'select#spdates', function (evt) {
console.log($().jquery);
var date = $(this).find(":selected").attr("data-date");
if (date=="new") {
//new date selected, discard what's in the boxes and blank values
$(".namspani").val("");
}
else {
//different date selected, discard what's in the boxes and blank values
alert($("#eventNames").find("[data-date='"+date+"']").text());
var spnamedom = $("#spname");
spnamedom.attr('value', 'new value'); //grab from other lists
$("#sptext").val($("#eventText").find("[data-date='"+date+"']").text());
$("#spdate").val(date);
$("#spimage").val($("#eventImagess").find("[data-date='"+date+"']").text());
}
});
});
the code i didn't include is acts on bits of html that look like this
<p>
<label for="s3image">Image 3:</label><br />
<input type="text" class="img ani1" name="widget-namsoc_nextmeet_widget[__i__][s3image]" id="s3image" value="" />
<input type="button" class="select-img3" value="Select Image" />
</p>
What it does is open the Wordpress image uploader dialog when you click a button. When "insert into post" is pressed it sets the path value into the field.
This code works. So what is so different to the other code that makes it fail?

Submit a value from dropdown without refresh then use the value re calculate a price

I have a select option to add accessories to a product. What I want to do is recalculate the price without have to refresh the page. This is what I'v got so far:
<form action="" method="post">
<select name="option" onchange="this.form.submit()">
<option value="15">Acc1</option>
<option value"30">Acc2</option>
<option value"45">Acc3</option>
</select>
</form>
$oldprice ='678';
$option = $_POST['option'];
$newPrice= $oldprice + $option;
This works great, however it has to refresh the page. Is there a way to recalculate the new price without having to refresh the page.
And also use the option value in other places on the page for example
If ($_POST['option] == '15'){ \do something}
Any help welcome
You could use ajax or if the needed information is already in the page which it seems to be based on your example code, then you could change the onchange to be a function:
onchange='updatePrice()'
Sample function code:
function updatePrice(){
var e = document.getElementsByName("option")[0];
var accessory_value = e.options[e.selectedIndex].value;
//additional code to update the price where
}
Hook onchange event in select tag.
Ex:
<select onChange="calculate(e)">
// option here
</select>
*.js:
function calculate(e) {
console.log(e.target.value);
}

How do I get jquery validation errors to display on a bootstrap-combobox?

I've been using this very cool bootstrap-combobox from here: https://github.com/danielfarrell/bootstrap-combobox
I currently have a .NET MVC 5 project which is using its out of the box validation (jquery unobstrusive validation), and any validation errors do not show up with the combobox control. My question is similar to the one here (unfortunately it has no answers): boostrap combobox validation - is it possible?
I took some time to create a jsfiddle for it: http://jsfiddle.net/1doe359f/3/
HTML:
<form id="experiment" action="/" method="post">
<div class="form-group">
<label class="control-label" for="PersonID">Person</label>
<select class="form-control combobox" data-val="true" data-val-required="This field is required." id="PersonID" name="PersonID">
<option value=""></option>
<option value="5">Bruce Banner</option>
<option value="9">Bugs Bunny</option>
<option value="8">Daffy Duck</option>
<option value="10">Elmer Fudd</option>
<option value="6">Jean Grey</option>
<option value="4">Clark Kent</option>
<option value="3">Peter Parker</option>
<option value="7">Scott Summers</option>
</select> <span class="field-validation-valid" data-valmsg-for="PersonID" data-valmsg-replace="true"></span>
</div>
<p>
<button type="submit" value="Save" role="button" class="btn btn-default" aria-disabled="false">Save</button>
</p>
Javascript:
var validator = {};
$(document).ready(function () {
$('.combobox').combobox();
var $form = $("#experiment");
// prevent form submission
$form.submit(function (e) {
e.preventDefault();
return false;
});
validator = $form.validate();
});
If you remove "combobox" from the control's class and hit the save button, you can see the error message pop up, as it should. It does not show up when the control is a combobox, however.
How can I get the validator errors to display while using this combobox control?
Usually I can stumble through this kind of thing, but this has a few too many moving parts for a javascript novice like myself. Any help would be appreciated!
I have used errorPlacement within that validate function to handle controls that are particularly whiny.
errorPlacement: function (error, element) {
// Set positioning based on the elements position in the form
var elem = $(element);
// Check we have a valid error message
if (!error.is(':empty')) {
if (elem.is(':combobox')){...logic here}
There have also been controls that I have used that have a container around them, that causes the error to be hidden instead of showing up on the container.
I did get this working eventually, but it's not a pretty solution. I made this change in the bootstrap-combobox code:
/* COMBOBOX PLUGIN DEFINITION
* =========================== */
$.fn.combobox = function ( option ) {
return this.each(function () {
var $this = $(this)
, data = $this.data('combobox')
, options = typeof option == 'object' && option;
if (!data) { $this.data('combobox', (data = new Combobox(this, options))); }
if (typeof option == 'string') { data[option](); }
/* Added stuff to get jquery validation working */
data.$element.attr("name", data.$source.attr("id"));
data.$element.attr("data-val", data.$source.attr("data-val"));
data.$element.attr("data-val-required", data.$source.attr("data-val-required"));
data.$element.closest("form").removeData("validator").removeData("unobstrusiveValidation");
$.validator.unobtrusive.parse(data.$element.closest("form"));
});
};
The gyst here is that I copy the relevant attributes (name, data-val, data-val-required) from the original dropdown ($source) to the combobox control ($element), and then I reset the validator so that it recognizes this newly-made control.
FYI: This is not a great approach because it creates a dependency to jquery validator in the bootstrap-combobox, and it is inflexible (will only do a 'required' check). One reason I took this shortcut was that the control that is generated doesn't have any good identifiers, so it was much easier to use this banked reference.
It does work though, and if you're only doing 'required' checks on your combobox and only using jquery validation in your project, it is adequate. Hopefully it at least gives some insight to save someone time in the future.

Categories