Reputation: 29
I have this form the Powerrange field is used to create a URL, but the value needed is different to the input one! so we need to predefine them.
<form id="form">
<input type="text" id="powerrange"><br><br>
<input type="radio" name="location" value="store" checked/><label>America</label><br>
<input type="radio" name="location" value="store.au"/><label>Australia and Oceania</label><br>
<input type="radio" name="location" value="store.au"/><label>Africa</label><br>
<input type="radio" name="location" value="store.au"/><label>Asia</label><br>
<input type="radio" name="location" value="store"/><label>Europe</label><br><br>
Ok this is what I have so far:
function goToPage(){
var location = $('input[name=location]:checked').val();
var idConversions = {"100":14,"101":5000}
$('#powerrange').keyup(function(){
var correctId = idConversions[$(this).val()];
});
window.location.href = "http://"+location+".domain.com/catalog.aspx?section="+correctId+"";
}
Upvotes: 0
Views: 255
Reputation: 171700
EDITED ANSWER: replaces select>
with <input>
, validates input entry against textual values of current options.
var minLengthRanges = 10000;
var ranges = $('#powerrange option').map(function () {
var data = {
val: this.value,
section: $(this).text()
}
if (data.section.length < minLengthRanges) {
minLengthRanges = data.section.length;
}
return data
}).get();
var currVal = $('#powerrange option:selected').text();
$('#powerrange').replaceWith('<input id="powerrange" type="number" value="' + currVal + '"/>');
$('#powerrange').keyup(function () {
var val = this.value
if (!val || val.length < minLengthRanges) {
return;
}
var isValid = checkIsValidRange(val);
$('body').append('<p>Value is ' + (isValid ? '' : 'not') + ' a match</p>');
if (isValid) {
var url = '.........catalog.aspx?section=' + val;
$('body').append('<p>URL is ' + url + '</p>');
}
});
function checkIsValidRange(val) {
var isValidRange = false;
if (val && !isNaN(parseInt(val, 10))) {
isValidRange = $.grep(ranges, function (item, index) {
return item.section == val;
}).length;
}
return isValidRange;
}
Upvotes: 1
Reputation: 37481
You'll need to build a pre-defined array so that your code knows 100
= 14
. On keyup
, blur
, or submit
or some form event that works for you, take the value of the text field, lookup the right value in the array, and then build your final link.
Here's a jsfiddle sample of how it might be done
$(function(){
var idConversions = {"100":14,"101":5000}
$('#the-text-field').keyup(function(){
var correctId = idConversions[$(this).val()];
if( typeof correctId !== "undefined") alert(correctId);
});
});
If you need to maintain a similar array on server-side code, try to find a way to share the list so you're not defining the "conversion matrix" in two places. Like build the array server-side in php or something, print it as JSON.
Upvotes: 0