JQuery Searching for elements using dropdown list - javascript

I want to make it if you pick something in dropdown list except Condition, it will search all elements for that and show them.
my jquery:
$('#searchbtn').click(function(){
var e = document.getElementById("condition");
var strUser = e.options[e.selectedIndex].value;
$('.item').each(function(){
var itemcondition = $('.condition').html();
if (itemcondition === strUser.toLowerCase()){
$(this).show();
}
if (itemcondition !== strUser.toLowerCase()){
$(this).hide();
}
});
})
my html:
<select id="condition">
<option>Condition</option>
<option value="factory new">Factory New</option>
<option value="minimal wear">Minimal Wear</option>
<option value="field tested">Field Tested</option>
<option value="well worn">Well Worn</option>
<option value="battle scarred">Battle Scarred</option>
</select>
this is how element looks like:
<div class="item" data-keywords="m4a4 howl">
<div class="name">M4A4 Howl</div>
<div class="condition">Factory New</div>
<div class="price">800 000 coins</div>
<button>Buy</button>
</div>

Here is how you can fix it.
Your html attribute and javascript code should be changed. You should give option value with ID/slug of condition of your products -- it shouldn't have space as we will manage this data easier in the next step.
<select id="condition">
<option>Condition</option>
<option value="factory-new">Factory New</option>
<option value="minimal-wear">Minimal Wear</option>
<option value="field-tested">Field Tested</option>
<option value="well-worn">Well Worn</option>
<option value="battle-scarred">Battle Scarred</option>
</select>
and your products list should classes corresponding your selected option value like this.
<div class="item factory-new field-tested" data-keywords="m4a4 howl">
<div class="name">M4A4 Howl</div>
<div class="condition">Factory New</div>
<div class="price">800 000 coins</div>
<button>Buy</button>
</div>
And your javascript should be changed almost entirely. It's much easier to understand.
$('#searchbtn').click(function() {
var $condition = $("#condition");
var condition = $condition.val();
$('.item').hide();
$('.item.' + condition).show();
})
hope it helps.

Related

How to get option tag custom data value using pure JS?

function calculateDeliveryCharge()
{
var CA=document.getElementById("pickup");
var c=CA.options[CA.selectedIndex].getAttribute('data-area');
alert(c);
}
<div class="container">
<div class="row">
<div class="col-12">
<select id="pickup" placeholder="পিকআপ এলাকা নির্বাচন করুন">
<option value="">পিকআপ এলাকা.....</option>
<option value="300 Feet"data-area="1">৩০০ ফিট (300 Feet)</option>
<option value="Adabor" data-area="1">আদাবর(Adabor)</option>
<option value="Adarsha Nagar(Badda)"data-area="1">আদর্শ নগর(বাড্ডা)- Adarsha Nagar(Badda)</option>
<option value="Aftab Nagar"data-area="1">আফতাব নগর(Aftab Nagar)</option>
<option value="Aga Nagar"data-area="1">আগা নগর(Aga Nagar)</option>
<option value="Agargaon"data-area="1">আগারগাঁও(Agargaon)</option>
<option value="Ahalia-Uttara"data-area="1">আহালিয়া-উত্তরা(Ahalia-Uttara)</option>
<option value="Ahmed Nagar"data-area="1">আহমেদ নগর(Ahmed Nagar)</option>
<option value="Ainusbag"data-area="1">আইনুসবাগ(Ainusbag)</option>
<option value="Ainusbag-Dakshinkhan"data-area="1">আইনুসবাগ-দক্ষিণখান(Ainusbag-Dakshinkhan)</option>
<option value="Ajiz Market"data-area="1">আজিজ মার্কেট(Ajiz Market)</option>
<option value="Alatunnessa School Road"data-area="1">আলাতুন্নেছা স্কুল রোড(Alatunnessa School Road)</option>
<option value="Alubazar"data-area="1">আলুবাজার(Alubazar)</option>
<option value="Amin bazar"data-area="1">আমিন বাজার(Amin bazar)</option>
<option value="Apollo"data-area="1">অ্যাপোলো(Apollo)</option>
</select>
</div>
</div>
<button class="border-1 p-2 bg-danger text-white"onclick="calculateDeliveryCharge()">ডেলিভারি চার্জ দেখুন</button>
</div>
I want to get the custom data attribute "data-area" value, 1 expected is here but I am getting null every time. What is the problem in my code and what is the solution?
This is a bit easier.
document.querySelector('#pickup option:checked').dataset.area
If we use #pickup, we selecting by ID as you have above. But by also specifying option:checked, we're looking for the currently selected option. (:checked is a bit weird here, but it's consistent with how other input elements work, such as checkboes.) Next, if you want the area data option, we can access it on the dataset property directly.
If nothing is selected, or the option does not contain the data-area property, your result will be not as expected.
It is generally not a good idea to use inline event handlers.
Here's a snippet using event delegation.
// => onclick="calculateDeliveryCharge()" becomes
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.nodeName === `BUTTON`) {
const selectr = document.querySelector("#pickup option:checked");
// find the selected option using a css selector ^^^
// this statement returns the option element when something
// is selected, null if nothing is selected
console.clear();
if (selectr &&
selectr.dataset.area) {
// ^ a data attribute value can be found using the elements' "dataset"
return console.log(`Area: ${selectr.dataset.area}`);
}
console.log(`No area or nothing selected yet`);
}
}
<div class="row">
<div class="col-12">
<select id="pickup" placeholder="পিকআপ এলাকা নির্বাচন করুন">
<option value="">পিকআপ এলাকা.....</option>
<option value="300 Feet" data-area="1">৩০০ ফিট (300 Feet)</option>
<option value="Adabor" data-area="1">আদাবর(Adabor)</option>
<option value="Adarsha Nagar(Badda)" data-area="1">আদর্শ নগর(বাড্ডা)- Adarsha Nagar(Badda)</option>
<option value="Aftab Nagar" data-area="1">আফতাব নগর(Aftab Nagar)</option>
<option value="Aga Nagar" data-area="1">আগা নগর(Aga Nagar)</option>
<option value="Agargaon" data-area="1">আগারগাঁও(Agargaon)</option>
<option value="Ahalia-Uttara" data-area="1">আহালিয়া-উত্তরা(Ahalia-Uttara)</option>
<option value="Ahmed Nagar" data-area="1">আহমেদ নগর(Ahmed Nagar)</option>
<option value="Ainusbag" data-area="1">আইনুসবাগ(Ainusbag)</option>
<option value="Ainusbag-Dakshinkhan" data-area="1">আইনুসবাগ-দক্ষিণখান(Ainusbag-Dakshinkhan)</option>
<option value="Ajiz Market" data-area="1">আজিজ মার্কেট(Ajiz Market)</option>
<option value="Alatunnessa School Road" data-area="1">আলাতুন্নেছা স্কুল রোড(Alatunnessa School Road)</option>
<option value="Alubazar" data-area="1">আলুবাজার(Alubazar)</option>
<option value="Amin bazar" data-area="1">আমিন বাজার(Amin bazar)</option>
<option value="Apollo" data-area="1">অ্যাপোলো(Apollo)</option>
</select>
</div>
</div>
<button class="border-1 p-2 bg-danger text-white">ডেলিভারি চার্জ দেখুন</button>
</div>

HTML/JS/Django Hiding incompatible options from two picklists

I'm running a filter for my object on a django-run website.
I have two select fields, with dropdowns based on related models to my model that i'd like to sort.
The problem is that some options are incompatible with each another and i'd like to hide the options of the second picklist based on what the user has selected on the first one.
I feel like i am going to use some JS but i've never used it before.
1st picklist: tasks <option value = task_id>
2nd picklist: crafts <option value = craft_id>
I have prepared a dictionnary that holds all the compatible values of any option selected on the first picklist, if that can help !
useful_dictionnary = {
first_task_id = [list_of_compatible_craft_ids]
...
last_task_id = [list_of_compatible_craft_ids]
}
How can i get JS to look at the task_id selected on the first picklist, and hide the options from the second picklist that are not in this list ?
Would be great! Thanks !
Here is my picklists code, if that helps
<div class="form-group col-sm-4 col-md-3">
<label for="id_tasks">Tasks:</label>
<select class="form-control" id="id_tasks" name="task">
<option value="">---------</option>
<option value="1" selected="selected">Tie-job: Front-tie Marker</option>
<option value="2">Tie-job: Scrapmachine support trackman</option>
<option value="3">Tie-job: Plate Thrower</option>
<option value="4">Tie-job: New-tie Marker</option>
</select>
</div>
<div class="form-group col-sm-4 col-md-3">
<label for="id_craft">Craft:</label>
<select class="form-control" id="id_craft" name="craft">
<option value="" selected="selected">---------</option>
<option value="1">Senior Engineer</option>
<option value="2">Roadmaster</option>
<option value="3">Foreman</option>
<option value="4">Assistant Foreman</option>
<option value="5">Electrical Welder EA</option>
<option value="6">Oxygen Welder OA</option>
<option value="7">Railway Machine Operator (RMO)</option>
<option value="8">Truck Driver (Type A, B or C)</option>
</select>
</div>
This snippet should do the trick. Change compatibleIds to map the options for the second select based on the first one.
$(document).ready(function(){
$("#id_craft option:not([value=0])").hide();
});
$("#id_tasks").change(function(){
$("#id_craft").val("0");
$("#id_craft option:not([value=0])").hide();
var compIds = { 1: [ 1,2,3,4,5], 3 : [ 4,2,3,8,7], 4 : [ 7,9,1,5], 2 :[5,3,1,8]};
for(var i = 0; i < compIds[$("#id_tasks").val()].length; i++){
$("#id_craft option[value=" + compIds[$("#id_tasks").val()][i] + "]").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-sm-4 col-md-3">
<label for="id_tasks">Tasks:</label>
<select class="form-control" id="id_tasks" name="task">
<option value="0" selected="selected">---------</option>
<option value="1">Tie-job: Front-tie Marker</option>
<option value="2">Tie-job: Scrapmachine support trackman</option>
<option value="3">Tie-job: Plate Thrower</option>
<option value="4">Tie-job: New-tie Marker</option>
</select>
</div>
<div class="form-group col-sm-4 col-md-3">
<label for="id_craft">Craft:</label>
<select class="form-control" id="id_craft" name="craft">
<option value="0" selected="selected">---------</option>
<option value="1">Senior Engineer</option>
<option value="2">Roadmaster</option>
<option value="3">Foreman</option>
<option value="4">Assistant Foreman</option>
<option value="5">Electrical Welder EA</option>
<option value="6">Oxygen Welder OA</option>
<option value="7">Railway Machine Operator (RMO)</option>
<option value="8">Truck Driver (Type A, B or C)</option>
</select>
</div>
Small add-on as the original question was about a django dictionary object:
To use a django list or dictionnary in the javascript, it is pretty straightforward as the {{ django_variable }} works fine inside the script tags.
So the final JS for this django template page is:
$(document).ready(function(){
$("#id_craft option:not([value=0])").hide();
});
$("#id_tasks").change(function(){
$("#id_craft").val("0");
$("#id_craft option:not([value=0])").hide();
var compatibleIds = {{ my_python_dictionary }};
for(var i = 0; i < compatibleIds[$("#id_tasks").val()].length; i++){
$("#id_craft option[value=" + compatibleIds[$("#id_tasks").val()][i] + "]").show();
}
});

Handling Multiple ids in java script

Suppose I have following code:
<div class="topPagination">
<select id="itemsPage" onClick="changeItems(this.value);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<div id="mainContent">
</div>
<div class="bottomPagination">
<select id="itemsPage" onClick="changeItems(this.value);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<script>
function changeItems(itemsPage) {
want to get the id of the current <select> box.
}
</script>
how to get the id of the current box. like if select top select box or if i select bottom box.
Please help me to find a solution. I know with same ids is not the porper coding standard. But i have a situation like this.
This is not a valid HTLM code, all ids should be unique
But anyway you can use this code to get second checkbox
document.querySelectorAll('checkbox')[1];
if you need to browse through specific checkboxes, set them all some special class and use
document.querySelectorAll('.special_checkbox')[1];
If you "want to get the id of the current box", it will always be "itemsPage".
Having 2 objects in the DOM with the same ID is not valid HTML.
However, if you can change the DOM but can't change the IDs for some reason, you could do something like this:
<select id="itemsPage" onClick="changeItems(this);">
and then make your function:
function changeItems(select) {
// "select" is your element
// "select.value" is your value (that used to be passed in as "itemsPage"
}
Ultimately you should try and change one of the IDs, or use classes instead.
Try utilizing HTMLElement.dataset to substitute duplicate ids ; data-id="itemsPage-1" for first id=itemsPage ; data-id="itemsPage-2" for secondid=itemsPage ; pass selected element dataset.id at onClick event onClick="changeItems(this.value, this.dataset.id);"
function changeItems(itemsPage, id) {
console.log(itemsPage, id)
}
<div class="topPagination">
<select data-id="itemsPage-1" onClick="changeItems(this.value, this.dataset.id);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<div id="mainContent">
</div>
<div class="bottomPagination">
<select data-id="itemsPage-2" onClick="changeItems(this.value, this.dataset.id);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
I think I know what it is you're trying to but this is a shot in the dark.
If you can change from using id to class this will work just fine.
window.onload=function(){
var PageItems=document.getElementsByClassName('itemsPage');
for(var i=0; i<PageItems.length; i++){
//Set Event Listeners for each element using itemsPage class name
PageItems[i].addEventListener('change',changeItems,false);
}
}
function changeItems(){
// New selected index
var Selected=this.selectedIndex;
var changeItems=document.getElementsByClassName('itemsPage');
for(var i=0; i<changeItems.length; i++){
//Change all select options to the new selected index.
changeItems[i].selectedIndex=Selected;
}
}
<div class="topPagination">
<select class="itemsPage">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<div id="mainContent">
</div>
<div class="bottomPagination">
<select class="itemsPage">
<option value="07">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!

Get HTML attribute values using jQuery

<html>
<body>
<div class="block-a">
<label data-value="15" name=symptom">Group1</label>
<div class="clsfWrapper">
<label data-value="10" name=clsfName"> SubHeader1</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
<div class="clsfWrapper">
<label data-value="11" name=clsfName"> SubHeader2</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
</div>
<div class="block-a">
<label data-value="16" name=symptom">Group2</label>
<div class="clsfWrapper">
<label data-value="5" name=clsfName"> SubHeader1</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
<div class="clsfWrapper">
<label data-value="6" name=clsfName"> SubHeader2</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
</div>
</html>
</body>
What is the best way to find every select SubHeader and Group value? For example the first one:
Group value: 15
Subheader value: 10
Option value : 1
and second one:
Group value: 15
Subheader value: 11
Option value : 1
I have a very robust way to get those values and i was wondering if there was any easier and more certain way.
jQuery:
function getHtmlAttributes(){
$.each($('#page_visit_reg_new_colds_2 option:selected'), function(key, value){
var optionParent = $(this).parent();
var selectParent = optionParent.parent();
var divParent1 = selectParent.parent();
var divParent2 = divParent1.parent();
var subheaderName = divParent1.parent().find('label[name=clsfName]').data('value');
var groupName = divParent2.parent().find('label[name=symptom]').data('value');
});
EDIT Changed label value to data-value
This instead of going from the option and then with parent up to the group, will start from the block and go down to the selected option.
It is still cycling trough the elements but is not using parent()
$.each($('.block-a'), function(){
var groupName = $(this).find("label[name='symptom']").data('value');
$.each($(this).find(".clsfWrapper"), function(){
var subheaderName = $(this).find("label[name='clsfName']").data('value');
$.each($(this).find('select option:selected'), function(){
var optionvalue = $(this).val();
});
});
});
On the JSFiddle i've added console log so you can check if everything is what you expect.
Since you're using the data attribute, just use this jQuery syntax:
$("#elementName").data("DataAttribute");
To get the value from the following label (IDs are better than names):
<label data-value="11" id="clsfName"> SubHeader2</label>
Use this:
var dataValue = $("#clsfName").data("value");

Jquery/Js: Hide/Show Divs based on select box option values

These are Dynamic dependent select controls. The sets of values of (1-3, 4-6, 7-9) determine the use hide/show divs function. The problem is the function i have only hide/show depending on the div id. How can i make the function hide/show div depended on the values(1-3, 4-6, 7-9) found in the selectbox?
Jquery
$('#select').change(function() {
$('#sub1, #sub2, #sub3').hide();
$('#sub' + $(this).find('option:selected').attr('id')).show();
});
Html Setup
<html>
<select size="6" id="category">
<option value="">categories 1-3 </option>
<option value="">----</option>
<option value="">----</option>
</select>
<div id="sub1" style="display:none">
<select name="subc1" size="6">
<option value="1">subcategories 4-6</option>
<option value="2">---</option>
<option value="3">---</option>
</select>
</div>
<div id="sub2" style="display:none">
<select name="subc2" size="6">
<option value="4">subcategories 7-9</option>
<option value="5">----</option>
<option value="6">----</option>
</select>
</div>
<div id="sub3" style="display:none">
<select name="subc3" size="6">
<option value="7">End</option>
<option value="8">----</option>
<option value="9">----</option>
</select>
</div>
</html>
select the value from drop down change function and do the operation depends on the value of drop down, following is the sample code
$(function() // Shorthand for $(document).ready(function() {
$('select').change(function() {
if($(this).val() == 1)
{
$('#sub1').hide();
$('#sub2').show();
}
});
});
You nee to change minor change in your category select
<select size="6" id="category">
<option value="1">categories 1-3 </option>
<option value="2">----</option>
<option value="3">----</option>
</select>
$('select#category').on('change', function() {
$('div[id=^sub]:visible').hide();
$('div#sub' + this.value).show();
});
can also use .change() instead of .on('change').
$('select#category').change(function() {
$('div[id=^sub]:visible').hide();
$('div#sub' + this.value).show();
});
NOTE:
$('div[id=^sub]:visible') will point to all divs that have id start with sub and visible.
You are trying with $('#select') which need to be $('#category') or $('select#category').
According to your comment:
Complete solution will look like following:
function isOnlyDashed(text) {
return text.replace(/-/g, '').length === 0;
}
$('select#category').change(function() {
var text = $('option:selected', this).text();
if (!isOnlyDashed(text)) {
$('div[id=^sub]:visible').hide();
$('div#sub' + this.value).show();
}
});
$('select[name^=subc]').change(function() {
var text = $('option:selected', this).text();
if (!isOnlyDashed(text)) {
$(this).parent() // jump to parent div
.next('div[id^=sub]:hidden') // go to next hidden div
.show();
}
});
Complete Workout
The problem with your code is that you have an incorrect selector.
$('#select')...
should be
$('select')...
Also, this part is wrong
$('#sub' + $(this).find('option:selected').attr('id')).show();
Replace it with this
$('#sub' + $(this).val()).show();
Finally, having different elements with the same name/id "sub1" is probably a bad idea, though technically not illegal. It is certainly confusing.
working demo http://jsfiddle.net/FwBb2/1/
I have made minor changes in your Jquery code as well as added value in your first select drop-down list which was missing rest hope this helps.
Please lemme know if I missed anything! B-)
code
$('select').change(function() {
$('#sub1, #sub2, #sub3').hide();
$('#sub' + $(this).val()).show();
});​
HTML
<html>
<select id="category">
<option value="1">categories 1-3 </option>
<option value="2">----</option>
<option value="3">----</option>
</select>
<div id="sub1" style="display:none">
<select name="subc1" size="6">
<option value="1">subcategories 4-6</option>
<option value="2">---</option>
<option value="3">---</option>
</select>
</div>
<div id="sub2" style="display:none">
<select name="subc2" size="6">
<option value="4">subcategories 7-9</option>
<option value="5">----</option>
<option value="6">----</option>
</select>
</div>
<div id="sub3" style="display:none">
<select name="subc3" size="6">
<option value="7">End</option>
<option value="8">----</option>
<option value="9">----</option>
</select>
</div>
</html>​

Categories