I'm having an issue with an assignment.
My for loop doesn't seem to run and I'm not sure what I've done wrong.
The variable dailyText prints "Weather Forecast" in a table but doesn't seem to enter the for loop. I'm not sure if this is a scoping issue or what's happening.
The script is supposed to take a number from a form option and create a table with that many rows.
Any help would be greatly appreciated!
function dailyInfo() {
var dailyText = "";
var numberDays = document.getElementById("numberDays").value; //https://stackoverflow.com/questions/23982774/turn-html-form-input-into-javascript-variable
dailyText += "<table class='table'><tr><th>Weather Forecast</th></tr>";
for (var i = 0; i < numberDays; i++) {
dailyText += "<tr><td>Day: " + (i + 1) + "</td>";
dailyText += "<td>" + dailyJsonObject.list[i].temp.min + "℃</td>";
dailyText += "<td>" + dailyJsonObject.list[i].temp.max + "℃</td>";
dailyText += "<td>" + dailyJsonObject.list[i].weather[0].description + "<img src ='http://openweathermap.org/img/w/'" + dailyJsonObject.list[i].weather[0].icon + ".png' /></td>";
}
document.getElementById("demo").innerHTML = dailyText;
dailyText += "</tr></table>";
}
<form id="numberDay">
<label id='numberDays'>Number of days requested</label>
<select name='numberDays'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
<button type="button" onclick="dailyInfo()">Submit</button>
</form>
</div>
<div id='demo'>
<table id="tableDaily"></table>
</div>
You have named the label with the id required for the numberDays. This means the loop was using the label value not the actual input as expected.
See below for alteration:
<form id="numberDay">
<label id='numberDays_label'>Number of days requested</label>
<!-- the select needs the id so the JS code can grab it!-->
<select name='numberDays' id="numberDays">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
<button type="button" onclick="dailyInfo()">Submit</button>
</form></div>
<div id='demo'>
<table id="tableDaily"></table></div>
You say:
var numberDays = document.getElementById("numberDays").value;
But actually the element you are getting is the label:
<label id='numberDays'>
So numberDays has actually the value undefined then.
Instead, you should do:
<label for='numberDays'>
and then:
<select name='numberDays' id='numberDays'>
That should actually at least start the loop. And then the label > select relationships is actually working, for example you can click now also the label to focus on the select.
Access a selected option:
HTML
<select name="" id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
</select>
JavaScript
var select = document.getElementById("mySelect"),
selectedOption = select.options[select.selectedIndex].text;
Get selected option text with JavaScript
In total (commented stuff)
function dailyInfo() {
var dailyText = "";
var numberDays = document.getElementById("numberDays");
numberDays = numberDays.options[numberDays.selectedIndex].text;
dailyText += "<table class='table'><tr><th>Weather Forecast</th></tr>";
for (var i = 0; i < numberDays; i++) {
dailyText += "<tr><td>Day: " + (i + 1) + "</td>";
dailyText += "<td>" + /*dailyJsonObject.list[i].temp.min +*/ "℃</td>";
dailyText += "<td>" + /*dailyJsonObject.list[i].temp.max +*/ "℃</td>";
dailyText += "<td>" + /*dailyJsonObject.list[i].weather[0].description*/ +"<img src ='http://openweathermap.org/img/w/'" + /*dailyJsonObject.list[i].weather[0].icon +*/ ".png' /></td>";
}
document.getElementById("demo").innerHTML = dailyText;
dailyText += "</tr></table>";
}
<form id="numberDay">
<label>Number of days requested</label>
<select id='numberDays' name='numberDays'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
<button type="button" onclick="dailyInfo()">Submit</button>
</form>
<div id='demo'>
<table id="tableDaily"></table>
</div>
Related
I am trying to make two drop down which populate by another dropdown
Here is code
html
<form type=get action="action.php">
<select name="meal" id="meal" onChange="changecat(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="" disabled selected>Select</option>
</select>
<input type="submit">
</form>
JavaScript
<script>
var mealsByCategory = {
A : {one:"Soup", two:"Juice"},
B : {three:"Water", four:"Others"},
C : {five:"Coffee", six:"Tea"}
};
function changecat(value) {
if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
else {
var catOptions = "";
for (categoryId in mealsByCategory[value]) {
catOptions += "<option value='" + mealsByCategory[value][categoryId] +"'>" + mealsByCategory[value][categoryId] + "</option>";
}
document.getElementById("category").innerHTML = catOptions;
}
}
</script>
I know my java script is not wrong.
I am looking for output like in dropdown value must be the object name and in the dropdrown the object value.
ie
when I click submit
site go
action.php?meal=B&category=Juice
Here you can see juice is passed (which apears on drop down) instead of it I need to pass "two" which is object name of juice
like action.php?meal=B&category=two
assign categoryId as value of options
var mealsByCategory = {
A: {
one: "Soup",
two: "Juice"
},
B: {
three: "Water",
four: "Others"
},
C: {
five: "Coffee",
six: "Tea"
}
};
function changecat(value) {
if (value.length == 0) document.getElementById("category").innerHTML = "<option></option>";
else {
var catOptions = "";
for (categoryId in mealsByCategory[value]) {
catOptions += "<option value='" + categoryId + "'>" + mealsByCategory[value][categoryId] + "</option>";
}
document.getElementById("category").innerHTML = catOptions;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form type=get action="action.php">
<select name="meal" id="meal" onChange="changecat(this.value);">
<option value="" disabled selected>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select name="category" id="category">
<option value="" disabled selected>Select</option>
</select>
<input type="submit">
</form>
I want to remove a specific value from an array.
For example:
var categories = ["Lenovo","Large","100"];
I displayed it like this
HTML CODE:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
How can I achieve this?
I tried it so many times but I failed because I cant get the value. You can check my code:
jQuery("#filter").val()
jQuery(function() {
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories = [];
if (brand) {
categories.push(brand);
}
if (screen_size) {
categories.push(screen_size);
}
if (cpu) {
categories.push(cpu);
}
if (memory) {
categories.push(memory);
}
if (price) {
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
var categories3 = "";
for (var i = 0; i < length; i++) {
var cat_id = "cat" + i;
categories3 += "<div class='filter_style'>" + categories[i] + "<a href='" + cat_id + "' id='" + cat_id + "' onclick='removeCat(event)'><span style='margin-left:15px;color:gray;' >x</span></a></div>";
jQuery("#filter").html(categories3);
}
});
});
function removeCat(evt) {
evt.preventDefault();
var catid = jQuery(this).attr('href');
var cat = jQuery(this).data("id");
//jQuery.grep(); maybe or indexOf first then slice() but I do not get the value
alert(catid);
}
You can simply remove element from array using below method
categories .splice( $.inArray(removeItem, categories), 1 );//removeItem is name of item which you want to remove from array
If you want to remove, for example, "Lenovo" from:
var categories = ["Lenovo","Large","100"];
do:
categories.splice(0)
I am looking to change the input type of a number selector to a dropdown if the value is less than 10. For values greater than 9 (10+) the input type should change back to a number selector.
Amazon and Sears.com are doing this style of quantity selectors in their shopping carts for some desktop users (subject to AB testing).
My issue is that it will change input type once, but not back again.
Additionally what is the best practice to retain the value between input types? I've considered either using a variable or copying to a hidden input which is the actual field submitted.
HTML:
<label class="mylabel">Quantity:</label>
<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">
<input type="submit" name="btnAddToCart" value="Add To Cart" id="btnAddToCart" class="">
jQuery:
$(".qty-input").change(function(){
if (parseInt(this.value) < 10){
$(".qty-input").replaceWith(
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>'
);
}
if (parseInt(this.value) > 9){
$(".qty-input").replaceWith(
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">'
);
}
});
There is no need to render and re-render the fields each time they should switch. It is easier to simply hide them.
A very basic solution, error handling and styling is up to you:
var high = $('#high')
var low = $('#low')
function onChange() {
if (low.is(':visible')) {
var value = low.val();
high.val(value);
if (parseInt(value) > 9) toggleInputs();
} else {
var value = high.val();
low.val(value);
if (parseInt(value) <= 9) toggleInputs();
}
}
function toggleInputs() {
$('#low').toggle();
$('#high').toggle();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Quantity:</label>
<input onchange='onChange()' id='high' style='display: none' />
<select onchange='onChange()' id='low'>
<option value='0'>0</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10+</option>
</select>
You can do it with two particular different selectors one for dropdown other for text to take getter than ten.selecting 10+ will change the select control name and it will be point to your textbox name or if want to switch back then restore the old name of select box and remove text box name.
Using jquery toggle method and prop attribute you can handle or modify name prop of the controls you are using.I think you got it.
Your server side code can catch the post data easily with this logic.
If not getting, can ask for sample code i can show you.
Although there are better ways of doing this I'm posting this to answer why your version is not working. Basically you're binding to an element that doesn't exist yet i.e. dynamic content.
Jquery handles this using the on method.
You can get it to work by adding a static ancestor and binding to that instead. For a better understanding of how event bubbling and delegation works check out this link. http://api.jquery.com/on/
Something like this
HTML
<label class="mylabel">Quantity:</label>
<div id="staticAncestor">
<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">
</div>
JS
$("#staticAncestor").on("change",'.qty-input',function(){
if (parseInt(this.value) < 10 && !$( "#txtQuantity" ).length){
$(".qty-input").replaceWith(
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>'
);
}
if (parseInt(this.value) > 9){
$(".qty-input").replaceWith(
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">'
);
}
});
Here is the pen http://codepen.io/anon/pen/jAQogj
Cheers and happy coding!
The problem is this...
once you remove the object from the DOM you are also removing the event handler if you still want to take the replace approach you would have to re-bind the event handler something like
$(document).ready(function() {
function test(){
if (parseInt(this.value) < 10) {
$(".container ").html(
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>'
);
} else {
$(".container").html(
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number">'
);
}
$(".qty-input").on('change', test);
}
$(".qty-input").on('change', test);
});
https://jsfiddle.net/happymacarts/pn1qeyg9/1/
This will work. Your example doesn't work since when you replace the DOM node/element, it no longer has the change event handled so function is bonded nor executed.
$(".qty-input").change(updateControl);
function updateControl(evt) {
var template;
if (parseInt(this.value) < 10 && this.tagName.toLowerCase() === "input") {
template =
'<select id="txtQuantity" name="txtQuantity" class="qty-input">' +
'<option value="1">1</option>' +
'<option value="2">2</option>' +
'<option value="3">3</option>' +
'<option value="4">4</option>' +
'<option value="5">5</option>' +
'<option value="6">6</option>' +
'<option value="7">7</option>' +
'<option value="8">8</option>' +
'<option value="9">9</option>' +
'<option value="10">10+</option>' +
'</select>';
} else if (parseInt(this.value) > 9 && this.tagName.toLowerCase() === "select") {
template =
'<input style="display: inline;" maxlength="3" min="1" pattern="\d+" autocomplete="off" name="quantityBox" class="qty-input" aria-label="Quantity" type="number" value="'+this.value+'">';
}
if (template) {
$(this).replaceWith(template);
$('.qty-input option[value='+this.value+']').attr('selected', true);
$('.qty-input').change(updateControl);
}
}
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<select id="txtQuantity" name="txtQuantity" class="qty-input">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10+</option>
</select>
check this out what I am telling Fiddle Demo
$(".select").on('click',function(){
if(isNaN($(this).val())){
$(this).addClass("hide");
$(".more").removeClass("hide");
$(this).removeAttr("name","quantity");
$(".more").attr("name","quantity");
} });
You may refine code to your purpose.
hi i have a select tag and i need if i click on any option from my first select.=====>i will get his attribute for it in the second select
my example is
<select name="select" >
<?php
$a={java,c++,php,python}
for($i=0;$i<4;$i++)
echo'<option value="'($i+1).'">'.$a[$i].' </option>';
}?>
</select>
<select name="select2" >
<?php
$after={{'j','jj','jjj'},
{'c','cc','ccc'},
{'p','pp','ppp'},
{'y','yy','yyy'}};
for($i=0;$i<3;$i++)
echo'<option value="'($i+1).'">'.$after[here the value of first select][$i].' </option>';
}?>
</select>
for example now if i chose java i need the select2 j jj jjj
if i chose c++ from the first select i need in the select 2 c cc ccc
i think it can be happen in jquerybut i don't know how it can be
Given your example, a possible output would be:
<select name="selectCode" >
<option></option>
<option value="1">java</option>
<option value="2">c++</option>
<option value="3">php</option>
<option value="4">python</option>
</select>
<br />
<select name="select2" style="display: none;">
</select>
The JQuery you want is:
var after = {};
after[1] = {0:"j",1:"jj",2:"jjj"};
after[2] = {0:'c',1:'cc',2:'ccc'};
after[3] = {0:'p',1:'pp',2:'ppp'};
after[4] = {0:'y',1:'yy',2:'yyy'};
$(function(){
$("select[name='selectCode']").on("change", function(){
console.log("selectCode Changed: " + $(this).val());
$("select[name='select2']").html("");
for(var i = 0; i<3; i++){
$("select[name='select2']").append("<option value='" + (i+1) + "'>" + after[$(this).val()][i] + "</option>").show();
}
});
});
jsFiddle example: http://jsfiddle.net/Twisty/xc4rs09m/
I have 2 selects and what i wanna do is (without refreshing the page): the moment the user selects a value from the first select (value1 or value2) changes the second select: if he choosed value1, then he have a select with values a, b, c, d; if he choosed value2, then he can choose on second select e, f, g, h.
Is this possible without refreshing the page?
Edit: I know you all are not here to write code for others; just wanted to keep it simple instead of posting all my messy code :). So, what i want to do, is to modify the second select id=selectAccessiblePaths with the onchange function applyGroupSelection()
function initDivWithConfig () {
divWithInfo = document.createElement('div');
divWithInfo.class = 'divWithInfoControls';
divWithInfo.style.position = 'absolute';
divWithInfo.style.top = '10px';
divWithInfo.style.width = '100%';
divWithInfo.style.textAlign = 'center';
var groupToDisplay = '<p id="pSelectGroup" style="display: block;">Select the user group: ';
groupToDisplay += '<select id="selectGroup" onchange="applyGroupSelection()">';
groupToDisplay += '<option selected>Nothing selected</option>';
for ( var g in userGroups ) {
groupToDisplay += '<option>' + g + '</option>';
}
groupToDisplay += '</select></p>';
divWithInfo.innerHTML += groupToDisplay;
groupSelected = 'group1';
var accessiblePathsToDisplay = '<p id="pSelectAccessiblePaths" style="display: none;">Select the accessible paths: ';
accessiblePathsToDisplay += '<select id="selectAccessiblePaths" onchange="applyAccessiblePathsSelection()">';
accessiblePathsToDisplay += '<option selected>Nothing selected</option>';
for ( var ap=0; ap<userGroups[ groupSelected ].accessiblePaths.length; ap++ ) {
var pathsForThisGroup = userGroups[ groupSelected ].accessiblePaths[ ap ][ "ns0:svg" ][ "groupPathsName" ];
accessiblePathsToDisplay += '<option>' + pathsForThisGroup + '</option>';
}
accessiblePathsToDisplay += '</select></p>';
divWithInfo.innerHTML += accessiblePathsToDisplay;
document.body.appendChild( divWithInfo );
}
function applyGroupSelection () {
groupSelected = "group2";
hideUnhideObject( "pSelectGroup" );
hideUnhideObject( "pSelectAccessiblePaths" );
}
Easy with HTML, CSS and a JavaScript line:
HTML:
<select id='firstselect' onchange="document.getElementById('secondselect').className=this.value">
<option value='select'>Select a value</option>
<option value='value1'>Value1</option>
<option value='value2'>Value2</option>
</select>
<select id='secondselect'>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
<option value='d'>d</option>
<option value='e'>e</option>
<option value='f'>f</option>
<option value='g'>g</option>
<option value='h'>h</option>
</select>
CSS:
#secondselect, #secondselect option {
display: none;
}
#secondselect.value1, #secondselect.value2 {
display: block;
}
.value1 option[value="a"], .value1 option[value="b"], .value1 option[value="c"], .value1 option[value="d"] {
display: block !important;
}
.value2 option[value="e"], .value2 option[value="f"], .value2 option[value="g"], .value2 option[value="h"] {
display: block !important;
}
See in action: http://jsfiddle.net/nukz3ns3/
UPDATED:
Also you can do a function for change to default value when firstselect change:
function setSecondSelect( select ){
var secondselect = document.getElementById('secondselect');
secondselect.className=select.value;
secondselect.selectedIndex = (select.value === 'value1')?0:4;
}
See how it works: http://jsfiddle.net/nukz3ns3/1/
Yes this is possible by using ajax post method.
Yes its possible if you used ajax.
http://api.jquery.com/jquery.ajax/
try this:
<script type="text/javascript">
$(document).ready(function () {
$("#select1").change(function() {
if($(this).data('options') == undefined){
$(this).data('options',$('#select2 option').clone());}
var id = $(this).val();
// alert(id);
var options = $(this).data('options').filter('[value=' + id + ']');
if(options.val() == undefined){
//$('#select2').hide();
$('#select2').prop("disabled",true);
}else{
//$('#select2').show();
$('#select2').prop("disabled",false);
$('#select2').html(options);
}
});
});
</script>
<div class="pageCol1">
<div class="panel">
<div class="templateTitle">Request for Items</div>
<table class="grid" border="0" cellspacing="0" cellpadding="0">
<tr class="gridAlternateRow">
<td><b>Item to be Request</b></td>
<td>
<select name="select1" id="select1">
<option value="1">--Select--</option>
<option value="2">Stationaries</option>
<option value="3">Computer Accessories</option>
<option value="4">Bottle</option>
<option value="5">Chair</option>
<option value="6">Office File</option>
<option value="7">Phone Facility</option>
<option value="8">Other Facilities</option>
</select>
</td></tr>
<tr><td>
<b>Category</b>
</td>
<td>
<select name="select2" id="select2" >
<option value="1">--Select--</option>
<option value="2">Note Books</option>
<option value="2">Books</option>
<option value="2">Pen</option>
<option value="2">Pencil</option>
<option value="2">Eraser</option>
<option value="2">Drawing sheets</option>
<option value="2">Others</option>
<option value="3">Laptop</option>
<option value="3">PC</option>
<option value="3">CPU</option>
<option value="3">Monitor</option>
<option value="3">Mouse</option>
<option value="3">Keyboard</option>
<option value="3">Mouse Pad</option>
<option value="3">Hard Disk</option>
<option value="3">Pendrive</option>
<option value="3">CD/DVD Writer</option>
<option value="3">RAM</option>
<option value="3">Mother Board</option>
<option value="3">SMPS</option>
<option value="3">Network Cables</option>
<option value="3">Connectors</option>
<option value="7">Land Line</option>
<option value="7">BlackBerry </option>
<option value="7">Other</option>
</select>
</td>
</tr>
</table>
</div>
</div>
</div>
your html can be of your required format.
If you are trying to populate the second select from existing options,
Try using filter() on a change handler
$("firstselect").change(function() {
var options = $("secondselect").filter(function() {
//return the options you want to display
});
$("secondselect").html(options);
});
Or if you want to retrieve options from server, use AJAX and form the options
and do an innerHTML as above.