Set option val based on array - javascript

I am trying to build a search that uses multiple drop downs. The script for the search uses the values for the first drop down and the second drop down. It works correct for Acura and MDX, but if I choose RLX it still passes MDX to the search as the value.
I know I have so somehow set for the value for the appended option to be whatever array is chosen in the second drop down, but I have had no luck. I am new to javascript so for all I know there may be a way easier than this to accomplish my goal.
FORM FOR SUBMIT
<form name="searchform" onSubmit="return dosearch();">
Brand:
<select id="brands">
<option val="Acura">Acura</option>
<option val="Chrysler">Chrysler</option>
</select>
<select id="item">
</select>
<input type="submit" value="Submit">
</form>
SCRIPT FOR URL STARTING WITH A BASE URL
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
location.href = baseUrl.concat('make='+ sf.brands.options[sf.brands.selectedIndex].value + '&&&&' + 'model=' + sf.item.options[sf.brands.selectedIndex].value + '&&&&' );
return false;
}
SCRIPT FOR DROP DOWNS
// JavaScript Document
$(document).ready(function(){
Acura=new Array("MDX","RLX","ILX","TLX");
Chrysler=new Array('200','3000','Town&Country');
populateSelect();
$(function() {
$('#brands').change(function(){
populateSelect();
});
});
function populateSelect(){
cat=$('#brands').val();
$('#item').html('');
eval(cat).forEach(function(t) {
$('#item').append('<option val="">'+t+'</option>');
});
}
});

Wow wow!
Please read some code style for js. If it works it doesnt mean that it's good.
DO NOT USE eval, EVER! eval = evil
You forgetting var declaration.
Inline handler in html bad practice too.
forEach will break in IE <= 8
concat is good, plus is good too
... lot of mistakes, that will cost you after.
I`ve wrote you a one liner, but it doesnt have structure. Just some ideas and removed a lot of things.
http://jsfiddle.net/gwEP5/
Whole js code:
$(function (){
// Selector
var $form = $("#searchform");
// it could be hashchange in the future
var setPath = function (url) {
window.location = url;
};
var searchHandler = function (e) {
e.preventDefault();
// You can serialize whole form just by .serialize
var url = window.location.pathname + "?" + $form.serialize();
setPath(url);
};
// Handlers, set handlers in js not in DOM, inline delegation is really nasty
// alias for .submit
$form.on("submit", searchHandler);
// Form elements
var $brands = $('#brands'),
$item = $("#item");
// Items list, dont use new Array or String. It`s good way in
var items = {
"Acura": ["MDX","RLX","ILX","TLX"],
"Chrysler": ['200','3000','Town&Country']
};
// eval is EVIL !!!! don`t use it ever
var populateItems = function () {
var elements = "",
value = $brands.val();
if (items[value] != null) {
$.each(items[value], function (i, item) {
elements += "<option value=\"" + item + "\">" + item + "</option>";
});
}
$item.html(elements);
}
// Alias .change
$brands.on("change", populateItems);
// init for start
populateItems();
});
Html form:
<form name="searchform" id="searchform">
Brand:
<select id="brands" name="make">
<option value="Acura">Acura</option>
<option value="Chrysler">Chrysler</option>
</select>
<select id="item" name="model">
</select>
<input type="submit" value="Submit"/>
</form>

The setup itself is fine. However, you have a typo:
sf.item.options[sf.brands.selectedIndex]
Should be:
sf.item.options[sf.item.selectedIndex]
Or, if you prefer the more aesthetic jQuery:
function dosearch() {
var baseUrl = 'http://www.spitzer.com/new-inventory/index.htm?';
var brand = $('#brands').find(":selected").text();
var item = $('#item').find(":selected").text();
location.href = baseUrl + 'make=' + brand + '&&&&' + 'model=' + item + '&&&&';
return false;
}

Related

Function variables don't work in jQuery?

Im making a jquery function, but im getting trouble with some variables. I cant get the value of #op1 to the input and in #z1 it shows "i" instead of "Start. Also the counter parameter doesnt add up. It only shows "0". In the click event it gets added up.
javascript code:
$(function() {
$(function () {
var inpreco = [];
var altpreco = [];
var cpcounter9 = 0;
$(".opcaopreco").click(function () {
SuperF(this, "#preco", "inpreco", "altpreco", "cpvalor", "cpindex",
"cpactive", "cpcounter9", "preco");
});
function SuperF(element, input, inpArray, secArray, inpValue, secIndex,
inpActive,
counter, msqlip) {
var inpValue = $("#" + element.id).val();
var secIndex = $("#" + element.id).data(secIndex);
var inpActive = $("#" + element.id).data(inpActive);
if (inpArray[0] == "") {
counter++;
$("#" + element.id + "l").addClass("activa");
$(element).data(inpActive, "primary");
inpArray[0] = (inpValue);
input.val(inpArray[0]);
}
$("#z1").html(inpArray[0]);
$("#z2").html(counter);
$("#z3").html(cpcounter9);
};
});
});
html code:
<input id="preco" type="text" name="preco" value=''><br><br>
<div id="op1l" class="input">
<input type="checkbox" id="op1" class="opcaopreco" value="Start" data-cpindex="1" data-cpactivo="">
<label for="op1"></label>
<span class="itext">Test</span>
</div>
<ul id="z">
<li id="z1">z1</li>
<li id="z2">z2</li>
<li id="z3">z3</li>
</ul>
You're passing in strings for your parameters, not elements. So when you index that parameter you're getting the first character in the string.
You need to use the strings as selectors to get their associated elements and then pass their return values into your function:
// use the strings to make a selection
var preco = $('#preco');
var inpreco = $('inpreco');
// etc.
// pass the results of each selection into your function
SuperF(this, preco, inpreco, ...)
You can do this inline as well:
SuperF(this, $("#preco"), $("inpreco"), ...)
Similarly, you have other variables you're trying to pass as strings, rather than passing them by name like this:
SuperF(this, $('#preco'), inpreco, altpreco, cpvalor, cpindex, cpactive, cpcounter9, preco);
That is the reason your function can't access most of the parameters and why your counter remains at 0.

How can I use an autosave partial view on a page with multiple forms?

Extending the example found at Autosave in MVC (ASP.NET), I wanted to create a partial to reuse in my application. I have one view with a tabbed layout, and each tab has its own form, and this is causing problems, namely that every form tries to submit every time, and only the first timestamp in the document updates. I understand why this is happening, but I don't know how I can fix it.
Partial's cshtml:
<div class="form-group">
<label class="control-label col-lg-2" for=""> </label>
<div class="col-lg-10">
<span class="help-block" id="autosaveTime">Not Autosaved</span>
</div>
</div>
#{
var autosaveString = "'" + #ViewData["autosaveController"] + "'";
if (ViewData["autosaveAction"] != null && ViewData["autosaveAction"] != "")
autosaveString += ", '" + ViewData["autosaveAction"] + "'";
}
<script type="text/javascript">
$(document).ready(function () {
autosave(#Html.Raw(autosaveString));
});
</script>
Javascript:
//methodName is optional-- will default to 'autosave'
function autosave(controllerName, methodName)
{
methodName = typeof methodName !== 'undefined' ? methodName : 'autosave'
var dirty = false;
$('input, textarea, select').keypress(function () {
dirty = true;
});
$('input, textarea, select').change(function () {
dirty = true;
});
window.setInterval(function () {
if (dirty == true) {
var form = $('form');
var data = form.serialize();
$.post('/' + controllerName + '/' + methodName, data, function () {
$('#autosaveTime').text("Autosaved at " + new Date);
})
.fail(function () {
$('#autosaveTime').text("There was a problem autosaving, check your internet connection and login status.");
});
dirty = false;
}
}, 30000); // 30 seconds
}
I have 2 ideas on how to fix it, but not sure which is more maintainable/workable:
Give each form an id, and pass that to the partial/autosave function. Add the name to the autosavetime text block for updates, and to determine which form to serialize/submit.
Somehow use jquery's closest function to find the form where the autosave block was placed, and use that to do what I was doing explicitly with #1.
First, make the URL using your Razor helper's Html extension (dynamically piecing URLs like this in JavaScript is unnecessarily risky). Take that, and stuff it in a data attribute on the tab control like so:
<div class="tab autosave" data-action-url='#Html.Action("Action", "Controller")'>
<form>
<!-- Insert content here -->
</form>
</div>
Then, you'll want something like this ONCE -- do not include it everywhere, and remove the javascript from your partial completely:
$(function() {
// Execute this only once, or you'll end up with multiple handlers... not good
$('.autosave').each(function() {
var $this = $(this),
$form = $this.find('form'),
dirty = false;
// Attach event handler to the tab, NOT the elements--more efficient, and it's always properly scoped
$this.on('change', 'input select textarea', function() {
dirty = true;
});
setInterval(function() {
if(dirty) {
// If your form is unobtrusive, you might be able to do something like: $form.trigger('submit'); instead of this ajax
$.ajax({
url : $this.data('action-url'),
data : $form.serialize()
}).success(function() {
alert("I'm awesome");
dirty = false;
});
}
}, 30 * 1000);
});
});

Adding params to the existing URL

Based on Adding a parameter to the URL with JavaScript i tried to make a script that adds parameters to the existing URL but kinda failed and i don't know why...
<script type="javascript">
function insertParam(key, value)
{
key = encodeURI(key); value = encodeURI(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
</script>
<label>
<select name="id" onchange="window.location='somepage.php?page=inserari-note&selected_value='+this.value">
<option>--Alege user--</option>
<?php
while($runrows = mysql_fetch_assoc($run))
{
$user = $runrows ['user_login'];
echo"<option value=\"$user\">$user</option>";
}
?>
</select>
</label>
<label>
<select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">
<option>--Alege Elev--</option>
<?php
while($runrows4 = mysql_fetch_assoc($run4))
{
$elev = $runrows4 ['Nume'];
echo"<option value=\"$elev\">$elev</option>";
}
?>
</select>
</label>
So the first select is populating the second select with students and also change the URL into somepage.php?page=inserari-note&selected_value='+this.value which works great but when i click on the options from the second select, nothing happens. In my opinion it should add at the existing URL which is the one i have mentioned before, the values &selected_valueelev="chosen-option" so that the URL should look like let's say somepage.php?page=inserari-note&selected_value=user&selected_valueelev=student. What am i doing wrong?
You should define script tag by the following:
<script type="text/javascript">
...
</script>
And also you have a syntax bug in the following:
// remove + before this.value
<select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">

Form calculator using Each() and Children() in jQuery

Im trying to build a form that calculates a total price based on a series of drop down boxes with string values such as "This option costs £30" i know this is not ideal but im putting this together as a hack for an existing script
For the most part ive got it working however im not sure how to run the each function for each child of #productconfig
I can manually input each of the drop downs ids into an array and that makes the calculation but it would be good if it just worked with all the children of #productconfig
<code>
<div id="#productconfig">
<label>Model Type</label>
<select name="products[220][data][modeltype]" id="data-modeltype-220">
<option value="M-Type £500">M-Type £500</option>
<option value="P-Type £500">P-Type £500</option>
<option value="S-Type £500">S-Type £500</option>
</select>
</div>
</code>
<code>
$(document).ready(function() {
$("#productconfig").children().change(function () {
calculateoptions();
});
calculateoptions();
});
</code>
<code>
function calculateoptions() {
var arr = ["data-modeltype-220"];
var total = 0;
jQuery.each(arr, function () {
var str = $('#' + this).attr("value");
var poundsign = str.indexOf('£');
var poundsign = poundsign + 1;
var lengthofstr = str.length;
var shortstr = str.substr(poundsign, lengthofstr);
total = eval(total) + eval(shortstr);
});
$('#price').html("£" + total);
}
</code>
How about this:
function calculateoptions() {
var total = 0;
jQuery('#productconfig select').each(function () {
total += $(this).val().match(/£(\d+)/)[1];
});
$('#price').html("£" + total);
}
You can use:
$("#productconfig select").each(function(){...});
To select each drop down in the product config div.

jquery removing string parts from two areas

I'm looking to expand on a recent script i've coded using jquery.
I have this following code
<script type='text/javascript'>
added_departments = new Array();
$("#departments_submit").click(function(){
var depo = $("#depo_list").val();
if(jQuery.inArray(depo, added_departments) != -1)
{
return false;
}
else
{
added_departments.push(depo);
$("#depo_added_list").append("<li>" + depo + "<a href='#' title='"+ depo +"' class='remove_depo'> [X] </a></li>");
var current_value = $("#departments").val();
if(current_value)
{
$("#departments").val(current_value + "," + depo);
}
else
{
$("#departments").val(depo);
}
return false;
}
});
</script>
The above code takes information selected in a select drop down box, adds it to a div to display publicly and also into a hidden form field that processes the data.
i've tried to create now something that will reverse this effect and remove certain selections from the div and the field. which is where i have this code
<script type='text/javascript'>
$(".remove_depo").click(function(){
var removing = $(this).title();
var current_val = $("#deparments").val();
if(current_val == removing) {
$("departments").replace(removing, "");
}
else {
$("departments").replace("," + removing, "");
}
});
</script>
It doesn't cause any errors, but it doesn't do anything either? So I'm really stuck. Any ideas?
EDIT: Updated code
$(".remove_depo").click(function(){
var removing = $(this).attr('title');
var current_val = $("#deparments").val();
if(current_val == removing) {
$("#departments").replace(removing, "");
}
else {
$("#departments").replace("," + removing, "");
}
});
Here is the html
<form method="post" action="javascript:void(0);">Select Departments To Be Added:
<div class="depo_adder">
<select id="depo_list"><option value="">--- INDIVIDUAL TAGS ---</option><option value="blah">blah</option></select>
<button id="departments_submit">Go!</button>
</div></form><form method="post" action="briefings/addbriefing.php">
<div class="form">
<strong>Departments: </strong>
<ul id="depo_added_list"><li>blah [X] </li></ul>
<input name="departments" id="departments" value="blah" type="hidden">
</div>
you're referring to $('departments') - this won't work. You need to specify either an identifierm eg $('#departments') or a class, eg $('.departments)
ah - other answer is also correct, .title() is not a function. You want
$('#foo').attr('title') to get the title.

Categories

Resources