I got this problem...I have an input which works as searcher and when I write something it show an ul with the list of matches and it works,
the <ul> and <li> items are generated with PHP via AJAX
This is my input
<input type="text" class="form-control" id="searchProduct" placeholder="Search..." />
This is the <ul>
<ul id="list">
<li id="match1" class="itemList"></li>
<li id="match2" class="itemList"></li>
<li id="match3" class="itemList"></li>
</ul>
After the list is generated the focus is still on the input and it's ok but I would like to use the arrow keys (up and down) to select one of the items
And I'm trying with code that I see in another answer but it is not working for me, I know that I'm doing something wrong but i can't figure out what the problem is... this is the javascript code
var li = $('#list > li');
var liSelected;
$(window).on('keydown', function(e){
if(e.which === 40){
if(liSelected){
liSelected.removeClass('background');
next = liSelected.next();
if(next.length > 0){
liSelected = next.addClass('background');
}else{
liSelected = li.eq(0).addClass('background');
}
}else{
liSelected = li.eq(0).addClass('background');
}
}else if(e.which === 38){
if(liSelected){
liSelected.removeClass('background');
next = liSelected.prev();
if(next.length > 0){
liSelected = next.addClass('background');
}else{
liSelected = li.last().addClass('background');
}
}else{
liSelected = li.last().addClass('background');
}
}
});
NEW INFO:
$('#searchProduct').keyup(function() {
var search = $(this).val();
if (search != '') {
$.ajax({
type: 'post',
cache: false,
url: '../includes/procedures/autocomplete.php',
data: { search: search },
success: function(datos) {
$('#coincidenciasBusqueda').show();
$('#coincidenciasBusqueda').html(datos);
}
});
}
});
you can use the build-in datalist to achieve arrow key select
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
<input type="submit">
I give your window's function a arguments to catch the value, every time when you press arrow key. and print it out. just like below.
var li = $('#list > li');
var liSelected;
$(window).on('keydown', function(e){
var selected;
if(e.which === 40){
if(liSelected){
liSelected.removeClass('background');
next = liSelected.next();
if(next.length > 0){
liSelected = next.addClass('background');
selected = next.text();
}else{
liSelected = li.eq(0).addClass('background');
selected = li.eq(0).text();
}
}else{
liSelected = li.eq(0).addClass('background');
selected = li.eq(0).text();
}
}else if(e.which === 38){
if(liSelected){
liSelected.removeClass('background');
next = liSelected.prev();
if(next.length > 0){
liSelected = next.addClass('background');
selected = next.text();
}else{
liSelected = li.last().addClass('background');
selected = li.last().text()
}
}else{
liSelected = li.last().addClass('background');
selected = li.last().text()
}
}
console.log(selected)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<style>
.background{
background: hsla(0, 100%, 0%, 0.4);
}
</style>
</head>
<body>
<input type="text" class="form-control" id="searchProduct" placeholder="Search..." />
<ul id="list">
<li id="match1" class="itemList">1</li>
<li id="match2" class="itemList">2</li>
<li id="match3" class="itemList">3</li>
</ul>
</body>
</html>
If you want to set to your input box, just give selected's value to it or you also can replace selected to $('searchProduct').
You could use jquery autocomplete along with ajax and PHP via JSON.
So now you can use the arrow keys to select. You can also do some CSS to customize the drop-down's look and feel.
I think you're looking for something like:
$(function(){
var li = $('#list li'), n = -1, ll = li.length-1;
$('#searchProduct').keypress(function(e){
var x = e.which;
li.removeClass('background');
if(x === 40 || x === 39 || x === 38 || x === 37){
if(x === 40 || x === 39){
n++;
if(n > ll)n = 0;
}
else if(x === 38 || x === 37){
n--;
if(n < 0)n = ll;
}
var ci = li.get(n);
ci.addClass('background'); $(this).val(ci.text());
}
});
});
Related
I have a set of input elements within 2 span block. I need to automatically select next input element by using onKeup(). This works fine until span tag is found. After that it is not detecting.
In the following code next input element is detected until 3rd input box after that it is not detected.
Can any one help with this?
http://jsfiddle.net/et3escuh/8/
<span>
<input id="opnamenummer6" class="form-control" type="text" name="opnamenummer6" value="" maxlength="1">
<input id="opnamenummer7" class="form-control" type="text" name="opnamenummer7" value="" maxlength="1">
<input id="opnamenummer8" class="form-control" type="text" name="opnamenummer8" value="" maxlength="1">
</span>
<script type="text/javascript">
$('input[class*="form-control"]').keyup(function(event) {
var $this = $(this);
var currentLength = $this.val().length;
var maximumLength = $this.attr('maxlength');
// if we've filled up this input, go to the next if only numerics are entered.
if ( (currentLength == maximumLength) && ((event.which >= 48 && event.which <= 57) || (event.which >= 96 && event.which<= 105))) {
$this.next().select();
}
//go to previous input if Backspace or Delete buton is pressed
if(event.which == 8 || event.which == 46) {
$(this).val('');
$(this).prev('input').select();
}
});
</script>
Don't use next(), use eq() and add or subtract to the index
$('input[class*="form-control"]').keyup(function(event) {
var $this = $(this);
var currentLength = $this.val().length;
var maximumLength = $this.attr('maxlength');
if ( (currentLength == maximumLength) && (!isNaN(this.value))) {
$('input').eq($(this).index('input') + 1).select();
}
if(event.which == 8 || event.which == 46) {
$(this).val('');
$('input').eq($(this).index('input') - 1).select();
}
});
FIDDLE
I'm stuck on a problem here that I've been trying to d/dx. I have a layout for an inventory page, and the css is set up to properly to make it display correctly. Let me start off with the html/php code:
<div class='container-fluid second-row'>
<div class='row' id='truckviewer-content'>
</div>
<div id="display">
<div class='row content' id='content'>
<div class='col-md-2 col-md-offset-2 page-title hidden-sm hidden-xs'>
<h1 class='page-title-top'>Inventory</h1>
</div>
<div class='col-md-6'>
<h3 class='page-sub-title'>Pick Your Rig</h3>
<p>
Not only does Lone Mountain Truck Leasing provide a great selection of reliable semi trucks for sale, usually 3-5 years old, we also ensure your satisfaction because we encourage you to drive the truck off the lot for diagnostic evaluations and required inspections.
</p>
<p>
Our inventory includes fleets of semi trucks for sale, so take a look at just a few samples of our current inventory, and if you find something you like, give us a call toll-free at 866.512.5685, or contact us with the form below.
</p>
</div>
</div>
<div class='row'>
<div class='col-md-10 col-md-offset-1'>
<form class='form-inline center' role='form'>
<h3 class='inventory-sub-title'>Filters</h3>
<div class='form-group'>
<select id='yearFilter' class='filter form-control'>
<option value="allY" selected>-- year --</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
</select>
</div>
<div class='form-group'>
<select id='makeFilter' class='filter form-control'>
<option value="allM" selected>-- Make --</option>
<option value="freightM">Freightliner</option>
<option value="intM">International</option>
<option value="kenM">Kenworth</option>
<option value="mackM">Mack</option>
<option value="peteM">Peterbilt</option>
<option value="volvoM">Volvo</option>
</select>
</div>
<div class='form-group'>
<select id='engineFilter' class='filter form-control'>
<option value="allE" selected>-- Engine --</option>
<option value="catE">Caterpillar</option>
<option value="cumE">Cummins</option>
<option value="detE">Detroit</option>
<option value="mackE">Mack</option>
<option value="volE">Volvo</option>
</select>
</div>
<div class='form-group'>
<select id='transFilter' class='filter form-control'>
<option value="allT" selected>-- Transmission --</option>
<option value="10T">10 Speed</option>
<option value="13T">13 Speed</option>
<option value="18T">18 Speed</option>
<option value="autoT">Auto</option>
</select>
</div>
<div class='form-group'>
<select id='apuFilter' class='filter form-control'>
<option value="allA" selected>-- APU --</option>
<option value="apuYes">Yes</option>
<option value="apuNo">No</option>
</select>
</div>
Show All
</form>
</div>
</div>
<?
$truckorder = file_get_contents("truckorder.tpl");
$truckorder = preg_replace('/\s+/', ' ', trim($truckorder));
$tagname = "truckorder";
$trucks = parseContent($truckorder, $tagname);
$trucks = explode("|", $trucks);
foreach($trucks as $truck){
$truck = preg_replace('/\s+/', ' ', trim($truck));
$quickview = file_get_contents("groups/group_$truck/content/quickview.tpl");
$quickview = preg_replace('/\s+/', ' ', trim($quickview));
$tagname = "quickfilter";
$filter = parseContent($quickview, $tagname);
$tagname = "quicktitle";
$title = parseContent($quickview, $tagname);
$tagname = "quickprice";
$price = parseContent($quickview, $tagname);
$tagname = "quicklook";
$specs = parseContent($quickview, $tagname);
$detailview = file_get_contents("groups/group_$truck/content/detailview.tpl");
$detailview = preg_replace('/\s+/', ' ', trim($detailview));
$tagname = "trucks";
$params = parseContent($detailview, $tagname);
$param = explode("|", $params);
$param1 = $param[0];
$param2 = $param[1];
$param3 = $param[2];
$param4 = $param[3];
$instock = getTruckTotals($param2,$param3,$param4);
?>
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 truck<?=$filter?>">
<div class="item ">
<p class='truck-img-align'>
<img class="truckTip" src="groups/group_<?=$truck?>/photos/quicktruck.png" border="no-border" />
</p>
<a class='ajax ajax-main' data-price="<?=$price?>" data-title="<?=$title?>" data-stock="<?=$instock?>" data-truck="<?=$truck?>" href="detail/?id=<?=$truck?>"><div class="caption"><h4>Quick Look</h4><?=$specs?></div></a>
</div>
<h3 class='truck-title'><?=$title?></h3>
<h3 class='truck-price'><?=$price?></h3>
<p class='in-stock'><?=$instock?></p>
<a class='ajax bottom-link' data-price="<?=$price?>" data-title="<?=$title?>" data-stock="<?=$instock?>" data-truck="<?=$truck?>" href="detail/?id=<?=$truck?>">Click or hover for more details</a>
</div>
<?
}
?>
</div>
</div>
EDIT: I have changed the javascript up. I have added a new sorting algorithm that is beginning to solve the problems that I am facing, but the error is now different.
$(function(){
sortDisplay();
});
// Image Overlay
$('.item').hover(function() {
$(this).find('div.caption').stop(false,true).fadeIn(200);
},
function(){
$(this).find('div.caption').stop(false,true).fadeOut(200);
});
// Filtering
$("#showAll").click(function(){
sortDisplay();
$(".truck").addClass("allY allM allE allT allA");
$("#yearFilter").val("allY");
$("#makeFilter").val("allM");
$('#engineFliter').val("allE");
$('#transFliter').val("allT");
$('#apuFliter').val("allA");
$(".truck").show();
// Update Filters
$("#yearFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allY'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#makeFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allM'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#engineFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allE'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#transFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allT'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#apuFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allA'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
});
$('.filter').change(function(){
sortDisplay();
$(".truck").each(function(){
$(this).removeClass("truck-reset");
});
$(".truck").addClass("allY allM allE allT allA");
var year = $("#yearFilter").val();
if(year !=='allY'){
$(".truck").removeClass("allY");
}
var make = $("#makeFilter").val();
if(make !=='allM'){
$(".truck").removeClass("allM");
}
var eng = $("#engineFilter").val();
if(eng !=='allE'){
$(".truck").removeClass("allE");
}
var trans = $("#transFilter").val();
if(trans !=='allT'){
$(".truck").removeClass("allT");
}
var apu = $("#apuFilter").val();
if(apu !=='allA'){
$(".truck").removeClass("allA");
}
$(".truck").hide();
$(".truck").each(function(){
if($(this).hasClass(year)&&$(this).hasClass(make)&&$(this).hasClass(eng)&&$(this).hasClass(trans)&&$(this).hasClass(apu)){
$(this).fadeIn();
}
});
//$("#anchor").slideto();
// Update Filters
$("#yearFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allY'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#makeFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allM'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#engineFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allE'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#transFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allT'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
$("#apuFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+':visible').size() < 1 && $(this).val() !=='allA'){
$(this).attr('disabled','disabled');
}
else{
$(this).removeAttr('disabled');
}
});
});
// Check If Filter Exists Else Disable Select Option
$("#yearFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allY'){
$(this).attr('disabled','disabled');
}
});
$("#makeFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allM'){
$(this).attr('disabled','disabled');
}
});
$("#engineFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allE'){
$(this).attr('disabled','disabled');
}
});
$("#transFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allT'){
$(this).attr('disabled','disabled');
}
});
$("#apuFilter option").each(function(){
var thisClass = $(this).val();
if($('.'+thisClass+'').size() < 1 && $(this).val() !=='allA'){
$(this).attr('disabled','disabled');
}
});
$('.ajax').click(function(e){
e.preventDefault();
var truckWindowId = $(this).data('truck');
var truckWindowTitle = $(this).data('title');
var truckWindowStock = $(this).data('stock');
var truckWindowPrice = $(this).data('price');
var content = {
id : truckWindowId,
title : truckWindowTitle,
stock : truckWindowStock,
price : truckWindowPrice
};
$.ajax({
url: "../assets/server/inventory/getTruckDetails.php",
type: "POST",
data: content,
dataType: "JSON",
cache: false,
success: function(data){
var images = data.images;
$('#display').fadeOut(function(){
$('#content').fadeOut();
$('#truckviewer-content').html(data.message).fadeIn();
//shut off the carousel autoscroll feature
$('.carousel').carousel({
interval: false
});
//allow for outside the box to be clickable and closer the div on click
$(document).mouseup(function(e){
var container = $(".truckview");
if(!container.is(e.target) && container.has(e.target).length === 0){
$('.closer').trigger("click");
}
});
});
}
});
});
$(function(){
$("#truckviewer-content").on('click', '.closer', function(e){
e.preventDefault();
var viewer = $('#close-button').data('toggle');
$(viewer).fadeOut(function(){
$('#content').fadeIn();
$('#display').fadeIn();
});
});
});
function sortDisplay(){
var count = 0;
var vizCount = 0;
if($(window).width() > 1200){
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
if(count <= 3){
if(count == 0 && $(this).is(':visible')){
vizCount++;
$(this).addClass('view-sort-left');
}else if(count == 3 && $(this).is(':visible')){
vizCount++;
$(this).addClass('view-sort-right');
}else if($(this).is(":visible")){
vizCount++;
}
}else if(count > 3){
if($(this).is(':visible')){
if(vizCount%4 === 0){
$(this).addClass('view-sort-left');
vizCount++;
}else if(vizCount%4 === 3){
$(this).addClass('view-sort-right');
vizCount++;
}else{
vizCount++;
}
}
}
count++;
});
}
}
EDIT: What's happening now is that when the second row of items gets checked the objects won't have the sorting classes of .sort-view-left or .sort-view-right appended to them, but they do in the first row. If you need further explanation please comment, and I'll answer.
This is all working properly but I'm sure I'm going to need to tweek it with what I am trying to figure out what to do.
When the items change display based on the filter that you pick, the css layout doesn't correct itself, that is because of the nth-child selectors used to pick them.
.truck{
width: 16%;
margin-left: 1%;
margin-right: 1%;
min-height: 350px;
margin-top: 25px;
}
.view-sort-left{
margin-left: 14% !important;
}
.view-sort-right{
margin-right: 14% !important;
}
.truck-reset:nth-child(4n-1){
margin-left: 14%;
}
With all that information above given, it is time to get to the point. What I'm trying to figure out is how do I change it up so that system is smart enough to decide how many objects are being shown on the inventory page, and then calculate a nice css table based on that. I'm almost considering just doing that from the get go. And then also calculate it based on page width as well. This might be too big of a problem to post on here. I'm not sure, i'm still kind of a noob at posts on here. if someone has an idea though let me know. If you think I should consolidate and shrink this problem down let me know that as well, and I can fix problems that way. I would like to put my brain together with someone on here though so that I can get to the bottom of this problem. Hope to hear from some people soon!
Figured it out, I needed to consolidate the two loops into just one and use options within the if statement to determine where my classes should go.
function sortDisplay(){
var count = 0;
var vizCount = 0;
if($(window).width() > 1200){
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
if((count == 0 || vizCount%4 == 0) && $(this).is(':visible')){
$(this).addClass('view-sort-left');
vizCount++;
}else if((count == 3 || vizCount%4 == 3)&& $(this).is(':visible')){
$(this).addClass('view-sort-right');
vizCount++;
}else if($(this).is(":visible")){
vizCount++;
}
count++;
});
}else if($(window).width() <= 1200 && $(window).width() > 992){
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
if((count == 0 || vizCount%3 == 0) && $(this).is(':visible')){
$(this).addClass('view-sort-left');
vizCount++;
}else if((count == 2 || vizCount%3 == 2)&& $(this).is(':visible')){
$(this).addClass('view-sort-right');
vizCount++;
}else if($(this).is(":visible")){
vizCount++;
}
count++;
});
}else{
$(".truck").each(function(){
$(this).removeClass('view-sort-left');
$(this).removeClass('view-sort-right');
});
}
}
$(window).resize(function(){
sortDisplay();
})
Hi i have a tab menu and i wanted to activate tab 2 when i click on a button from tab 1..
here is my javascript:
<link rel="stylesheet" type="text/css" href="http://oliveshades.com/dashboard_menu.css">
<script type='text/javascript' src="http://oliveshades.com/jquery.idTabs.min.js"></script>
<script type='text/javascript'>
function toggle_visibility(id) {
var thelist = document.getElementsByClassName("alist");
for (var i = 0; i < thelist.length; i++) {
thelist[i].style.display = 'none';
}
var e = document.getElementById(id);
if (e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}</script>
here is my HTML:
<div class="dashTab">
<ul class="idTabs">
<li>Statistics</li>
<li>Traffic</li>
</ul></div>
<div id="tab1"><input name="" type="button" value="redirect me to tab 2" /></div>
<div id="tab2">This is Tab2</div>
http://jsfiddle.net/UCjYS/
Try this:
function changeTab(arg){
switch(typeof arg){
case "number":
$('.idTabs > li:eq(' + arg + ') > a').click();
break;
case "string":
$('.idTabs > li:contains(' + arg + ') > a').click();
break;
}
}
http://jsfiddle.net/DerekL/UCjYS/1/
idTabs doesn't seem to have methods to activate a tab, but you can trigger it manually.
$('#tab1 input').click(function(){
$('li:contains("Traffic")').click();
return false;
});
How can I make it so Jquery checks that ESNStart and ESNEND in the HTML form are in the same range otherwise it throws an alert saying that both numbers need to be in the same range to the user after typing in the value for ESNEnd ??
I still don't understand how I could also make it so ESNList gets checked for all its multiple values entered in the text field to be in the same range otherwise it also throws an alert to the user to enter a number in the same range as shown by the if statements ? A fiddle demonstrating this would help me learn so much , thanks a bunch !
<html>
<head>
<script type="text/javascript" src="jquery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function() {
$(":text").css("border", "2px solid red");
$(":text").keyup(function() {
var enteredData = $(this).val()
console.log(enteredData);
if (enteredData == "") {
$(this).css("border", "2px solid red");
} else {
$(this).css("border", "inherit");
}
if ($(this).attr("id") == "ESNList") {
esnList = parseInt(enteredData);
switch (true) {
case (esnList >= 986329 && esnList <= 999999):
$("#ddl_StxName").val("stx2");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 660000 && esnList <= 699999):
$("#ddl_StxName").val("mmt");
$("#ddl_rtumodel").val("globalstar");
break;
case (esnList >= 200000 && esnList <= 299999):
$("#ddl_StxName").val("stm3");
$("#ddl_rtumodel").val("stmcomtech");
break;
case (esnList >= 1202114 && esnList <= 1299999):
$("#ddl_StxName").val("smartone");
$("#ddl_rtumodel").val("globalstar");
break;
}
}
});
});
</script>
</head>
<body>
<form id="provision">ESNList:
<input type="text" id="ESNList" name="ESNList" size="30" />
<br />ESN Start:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />ESN End:
<input type="text" id="ESNStart" name="ESNStart" size="10" />
<br />UnitName:
<input type="text" id="STxName" name="STxName" size="30" />
<br />Unit Model:
<select name="STxName" id="ddl_StxName">
<option value="stx2">STX2</option>
<option value="stm3" selected>STM3</option>
<option value="acutec">Acutec</option>
<option value="trackpack">Trackpack</option>
<option value="mmt">MMT</option>
<option value="smartone">Smartone</option>
<option value="smartoneb">SmartOneB</option>
</select>
<br />RTU Model Type:
<select name="rtumodel" id="ddl_rtumodel">
<option value="globalstar">GlobalStar</option>
<option value="both">Both</option>
<option value="comtech">Comtech</option>
<option value="stmcomtech">STMComtech</option>
</select>
<br />
<input type="submit" value="submit" />
</form>
</body>
</html>
I created some methods that seem to work, although I haven't created groups of numbers that are out of range.
I strongly suggest you don't allow user to enter comma separated lists as it will be hard to point to user the invalid entries. It would be a lot cleaner having each number in it's own input. You can easily add a button for "Add new number" and create a new input for it.
I used arrays to store ranges and the values for the valid range that get changed for other fields. This module is not trivial and suggest you create a testing sandbox with a wide variety of numbers you can test with.
$('#ESNList').keyup(function(){
var enteredData = $(this).val();
$(this).removeClass('valid');
if( enteredData == ''){
return;
}
if(hasMultipleValues(enteredData)){
var range=rangeCheckMultipleNumbers(enteredData)
if( range===false){
log('Numbers not in same range');
return;
} else{
setRangeValues(range);
$(this).addClass('valid');
}
}
var rangeIdx = getRangeIndex(enteredData);
if(rangeIdx===false){
log('Number not in range');
}else{
setRangeValues(rangeIdx);
$(this).addClass('valid');
}
});
function hasMultipleValues( str){
/* second test for a singel entry with comma at end*/
return str.indexOf(',') !=-1 && str.indexOf(',') != str.length-1;
}
var ranges = [
[986329, 999999],
[660000, 699999],
[200000, 299999],
[1202114, 1299999]
];
var rangeText = [
["stx2", "globalstar"],
["mmt", "globalstar"],
["stm3", "stmcomtech"],
["smartone", "globalstar"]
]
/* returns range index if all in same range, otherwise returns false*/
function rangeCheckMultipleNumbers(str) {
var nums = str.split(',');
var rangeMatch = true; /* clean array to remove empty values if extra commas*/
nums = $.grep(array, function(item, index) {
return parseInt(item);
});
var groupRange = getRangeIndex(nums[0]);
if(nums.length > 1) {
for(i = 1; i < nums.length; i++) {
if(!checkSameRange(nums[i - 1], nums[i])) {
rangeMatch = false;
}
}
}
return rangeMatch ? groupRange : false;
}
function setRangeValues(rangeIndex) {
$("#ddl_StxName").val(rangeText[rangeIndex][0]);
$("#ddl_rtumodel").val(rangeText[rangeIndex][1]);
}
function checkSameRange(num1, num2) {
return getRangeIndex(parseInt(num1, 10)) == getRangeIndex(parseInt(num2, 10));
}
/* returns false if out of range, otherwise returns range index*/
function getRangeIndex(num) {
var idx = false;
$.each(ranges, function(i, range) {
if(num >= range[0] && num <= range[1]) {
idx = i;
return false;
}
});
return idx;
}
DEMO: http://jsfiddle.net/hXsQ8/1/
I have this school assignment that I've been working on and am totally stumped as to why it's doing what it's doing. Basically it's a left selection list, 2 middle buttons, and a right selection list. The purpose is to move options between lists. My problem is as follows: a selection is made on left list, the move to right list button is clicked, an option is added to the right list named "undefined" and the selection on the left list disappears. I don't want anyone to do my homework for me, but tips and hints are greatly appreciated.
Here's my code:
<script type="text/javascript">
/* <![CDATA[ */
function moveRight() {
var leftCurText = document.forms[0].leftSide.selectedIndex.text;
var leftCurValue = document.forms[0].leftSide.selectedIndex.value;
var leftCurName = document.forms[0].leftSide.selectedIndex;
if (leftCurName != -1) {
var listName = new Option();
listName.text = leftCurText;
listName.value = leftCurValue;
nextItem = document.forms[0].rightSide.length;
document.forms[0].rightSide.options[nextItem] = listName;
document.forms[0].leftSide.options[leftCurName] = null;
} else if (document.forms[0].leftSide.length <= 0) {
window.alert("There are no more options in the left list")
}
else
window.alert("No option is selected on the left side");
}
function moveLeft() {
var rightCurText = document.forms[0].rightSide.selectedIndex.text;
var rightCurValue = document.forms[0].rightSide.selectedIndex.value;
var rightCurName = document.forms[0].rightSide.selectedIndex;
if (rightCurName != -1) {
var listName = new Option();
listName.text = rightCurText;
listName.value = rightCurValue;
nextItem = document.forms[0].leftSide.length;
document.forms[0].leftSide.options[nextItem] = listName;
document.forms[0].rightSide.options[rightCurName] = null;
} else if (document.forms[0].rightSide.length <= 0) {
alert("There are no more options on the right list")
} else
window.alert("No option is selected on the right side");
}
/* ]]>*/
</script>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link rel="Stylesheet" type="text/css" />
</head>
<body>
<h2>This page will switch items between lists</h2>
<div align="center">
<form action="">
<table border="3">
<tr>
<th>Left List</th>
<th>Click</th>
<th>Right List</th>
</tr>
<tr>
<td>
<select name="leftSide" size="6">
<option value="stephanie">Stephanie</option>
<option value="beatriz">Beatriz</option>
<option value="carol">Carol</option>
</select>
</td>
<td>
<input type="button" onclick="moveLeft()" name="leftButton" value="<<" /> <br />
<input type="button" onclick="moveRight()" name="rightButton" value=">>" />
</td>
<td>
<select name="rightSide" size="6">
<option value="evan">Evan</option>
<option value="david">David</option>
<option value="mark">Mark</option>
</select>
</td>
</tr>
</table>
</form>
</div>
</body>
You are trying to get properties from the selectedIndex property of the list, which is a number. You want to get it from theList.options[theList.selectedIndex].
EDIT:
Also, your variables are named rather confusingly. Try this:
var list = document.forms[0].rightSide;
var index = list.selectedIndex;
var text = list.options[index].text;
var value = list.options[index].value;
And one of the most striking things: your two functions are basically the same. Give the source list and target list as parameters to a general move() function.
Idk why the code is so messed up. Here's the functions:
Move Left:
function moveLeft() {
var rightCurText = document.forms[0].rightSide.selectedIndex.text;
var rightCurValue = document.forms[0].rightSide.selectedIndex.value;
var rightCurName = document.forms[0].rightSide.selectedIndex;
if (rightCurName != -1) {
var listName = new Option();
listName.text = rightCurText;
listName.value = rightCurValue;
nextItem = document.forms[0].leftSide.length;
document.forms[0].leftSide.options[nextItem] = listName;
document.forms[0].rightSide.options[rightCurName] = null;
}
else if (document.forms[0].rightSide.length <= 0) {
alert("There are no more options on the right list")
}
else
window.alert("No option is selected on the right side");
}
Move Right:
function moveRight() {
var leftCurText = document.forms[0].leftSide.selectedIndex.text;
var leftCurValue = document.forms[0].leftSide.selectedIndex.value;
var leftCurName = document.forms[0].leftSide.selectedIndex;
if (leftCurName != -1) {
var listName = new Option();
listName.text = leftCurText;
listName.value = leftCurValue;
nextItem = document.forms[0].rightSide.length;
document.forms[0].rightSide.options[nextItem] = listName;
document.forms[0].leftSide.options[leftCurName] = null;
}
else if (document.forms[0].leftSide.length <= 0) {
window.alert("There are no more options in the left list")
}
else
window.alert("No option is selected on the left side");
}