Add Remove element with Jquery using a refrence to html element - javascript

I am trying to add an element to a dropDown and after selection remove it, by naively trying to have htmlElement refrence defines as such : (Of course this doeasnt work)
var selectAnOption = "<option value='' selected='selected'>Select One</option>";
So later
var addSelectAnOption = function () { ('#ddb1').prepend(selectAnOption ); };
var removeSelectAnOption = function () { selectAnOption.remove(); };
I have also tried the following variation:
var selectAnOption;
var addSelectAnOption = function () { selectAnOption = $('#ddb1').prepend("<option value='' selected='selected'>Select One</option>"); };
var removeSelectAnOption = function () { selectAnOption.remove(); };
But this also didn't work, as selectAnOption was set to the dropDownBox itself
Of course I could add the option with an id and then later use that to find it to remove it, but that seemed not too pretty.

wrap it in $():
var selectAnOption = $("<option value='' selected='selected'>Select One</option>");
DEMO

Related

How to show / hide same option from other dropdown using jQuery or Javascript

I have 4 dropdown list <td> <select class="encoderSelect" id="encoder1"><option value="None">-- Select User Command --</option><option value="1920*1080">1920*1080</option> <option value="320*240 to 1280* 720">320*240 to 1280*720</option> <option value="720*480">720*480</option> <option value="320*240 to 1920*1080">320*240 to 1920*1080</option> </select></td>
there is another 3 dropdown also there id is like encoder2,encoder3 and encoder4. I want to hide a the options if it is selected in any 4 of this list. I used this code by call class name but its not worked.
$('.encoderSelect').change(function(){
var optionval = $('.encoderSelect').val();
console.log(optionval);
$(".encoderSelect option[value='"+optionval+"']").hide();
});
$('.encoderSelect').on("change", function(){
$('.encoderSelect:selected', this).hide().siblings().show();
}).trigger('change'); // this code also tried but not worked
can I implement this using class.? or I must go by using id..?
$('#encoder1').on("change", function(){
var selected = $('#encoder1').val();
for (var i = 0; i<$('#encoder1').children().length; i++) {
var element = $('#encoder1 option:eq('+i+')');
if ($(element).text() === selected) {
$(element).hide();
} else {
$(element).show();
}
}
});
demo
Please try this. I hope it works fine and helps your project.
<script>
$(document).ready(function() {
$('select.encoderSelec').on('change', function(event) {
var prevValue = $(this).data('previous');
$('select.encoderSelec').not(this).find('option[value="'+prevValue+'"]').show();
var value = $(this).val();
$(this).data('previous',value); $('select.encoderSelec').not(this).find('option[value="'+value+'"]').hide();
});
});
</script>
Demo

Update the select options with given dynamic data

Need to send dynamic (not hardcode) data to a select element.
This code works great in one of my sheets but doesn't work in the other sheet.
The "select" element doesn't get updated with the options I send..
I don't get an error message either.
I've spent a lot of time twitching it and trying to find why but still don't see what's wrong.
p.s. I used a dummy object to send the data for testing purpose.
The html (used MaterializeCss framework)
<select class="icons browser-default" id="selName" onChange ="getNameText();">
<option value="" disabled selected>Choose week</option>
<div id = "err"></div>
//select element initialization in framework
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var options = handlers()
var instances = M.FormSelect.init(elems);
});
function handlers() {
var success = google.script.run.withSuccessHandler(addOptions).getNamesForDropdown()
var failure = google.script.run.withFailureHandler(showError).getNamesForDropdown()
return;
}
function addOptions(names) {
var selectTag = document.getElementById("selName") //select tag
for (var k in names) {
var thisID = k;
var thisText = names[k];
var option = document.createElement("option"); //creating option
option.text = thisText
option.value = thisID;
selectTag.add(option);
}
}
function showError() {
var err = document.getElementById("err").innerHTML = "There was an error."
}
//get the text of selected option
function getNameText() {
var sel = document.getElementById("selName")
var nameText = sel.options[sel.selectedIndex].text;
return nameText;
}
Dummy object I send:
function getNamesForDropdown() {
var namesObj = {
one: "blah",
two: "blahblah"
}
return namesObj;
}
Here's the result what I get (on the screen you there's only hardcoded option):
I handled it. I added a class "browser-default" to the select and the options got updated. This class comes from MaterializeCss Framework.

Set option val based on array

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;
}

jquery function select custom attribute from select box

I am trying to get the custom attribute values from the select box. It is triggered by a checkbox click which I already have working. I can get the name and value pairs just fine. I want get the custom attributes (therapy) (strength) (weight) and (obstacle) from the option value lines. is this possible?
select box
<option value="2220" therapy="1" strength="1" weight="0" obstacle="0">Supine Calf/Hamstring Stretch</option>
<option value="1415" therapy="0" strength="0" weight="0" obstacle="0">Sitting Chair Twist</option>
<option value="1412" therapy="0" strength="0" weight="0" obstacle="0">Static Abductor Presses</option>
jQuery
// exercise list filter category
jQuery.fn.filterByCategory = function(checkbox) {
return this.each(function() {
var select = this;
var optioner = [];
$(checkbox).bind('click', function() {
var optioner = $(select).empty().scrollTop(0).data('options');
var index=0;
$.each(optioner, function(i) {
var option = optioner[i];
var option_text = option.text;
var option_value = parseInt(option.value);
$(select).append(
$('<option>').text(option.text).val(option.value)
);
index++;
});
});
});
};
You need to find the selected , like this:
var $select = $('#mySelectBox');
var option = $('option:selected', $select).attr('mytag');
That is how to get selected option attribute:
$('select').find(':selected').attr('weight')
Get selected option and use attr function to get the attribute:
$("select").find(":selected").attr("therapy")
JSFIDDLE

I am still new with JS and can't see my mistake for this basic calculation script

I got the code from
Calculate one variable based on changing input
I have written the following based on my limited understanding
<td>
<select name='breadstick'>
<option value='0' selected >-- Choose Breadstick --</option>
<option value='4.06'>Breadstick</option>
<option value='3.8'>Melba Toast</option>
</select>
</td>
<td>
<input id="input_bread" type="text" name="input_bread" style="width:50px;" onkeyup="do_calc3(this.value);">
</td>
<td>
<input id="bread_results" class="" readonly name="bread_results" style="width:50px;" value="" />
<script>
function do_calc3() {
var bread_choice = document.getElementById('breadstick');
var bread_weight = document.getElementById('input_bread');
var bread_r = bread_choice * bread_weight;
document.getElementById("bread_results").value = bread_r;
}
</script>
</td>
First:
You need to use the .value property for getting the elements' values.
Change:
var bread_r = bread_choice * bread_weight;
to:
var bread_r = bread_choice.value * bread_weight.value;
In your original code, bread_choice and bread_weight are references to DOM elements. When you try to multiply them, that won't be a numerical result.
You are attempting to get their values (what's selected in the dropdown and what's typed in the textbox), so you should get them with .value.
It's similar to your next line, where you set the bread_results element's value with .value = bread_r.
Second:
Your <select> element doesn't have an id of "breadstick", it has a name. So change your element to be:
<select id='breadstick' name='breadstick'>
or change your retrieval of the element to be:
var bread_choice = document.querySelector('select[name="breadstick"]');
Third:
Since you are using the inline event handler for onkeyup, you are already passing this.value, which means the textbox's value. Therefore, you don't need to get the textbox and its value in the function. Just add a parameter and use it.
function do_calc3(bread_weight) {
var bread_choice = document.getElementById('breadstick').value;
var bread_r = bread_choice * bread_weight;
document.getElementById("bread_results").value = bread_r;
}
Fourth:
You shouldn't use inline event handlers. For many reasons, it's better to handle events in your Javascript code. Here's an example of how I'd set it up. (note that the onkeyup="do_calc3(this.value);" was removed and done in the Javascript's window.onload event)
function do_calc3() {
var bread_choice = document.getElementById('breadstick');
var bread_weight = this;
var bread_r = bread_choice.value * bread_weight.value;
if (isNaN(bread_r)) {
bread_r = "Invalid";
}
document.getElementById("bread_results").value = bread_r;
}
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
window.onload = function () {
var textbox = document.getElementById("input_bread");
addEvent(textbox, "keyup", do_calc3);
};
DEMO: http://jsfiddle.net/Gtven/4/
<select name='breadstick' id='breadstick'>
Above needs to be changed, as you don't have an id "breadstick" yet.
Below is a changed function in order to get the actual values of the elements and not just the elements.
function do_calc3() {
var bread_choice = document.getElementById('breadstick').value;
var bread_weight = document.getElementById('input_bread').value;
var bread_r = bread_choice * bread_weight;
document.getElementById("bread_results").value = bread_r;
}
And here I got you a working Fiddle: http://jsfiddle.net/TwqC6/
Use .value:
var bread_choice = document.getElementById('breadstick').value;
var bread_weight = document.getElementById('input_bread').value;

Categories

Resources