custom tag containing data in option - javascript

I am having a list of stuff that the user can select. The way it's currently made, we have an integer as name, a price as value but i need to add a color. It's not unique so i cannot use ID.
example :
<option name='6' value="30.95">6 Orange(30.95$/month)</option>
<option name='6' value="33.95">6 Green(33.95$/month)</option>
<option name='10' value="32.95">10 Orange(32.95$/month)</option>
<option name='10' value="35.95">10 Green(35.95$/month)</option>
I need to combine two non-unique values and them to be accessible by jQuery / Javascript
I would like not to make two selects. I know it's straightforward the easiest solution but if i could stick to a single one that would give better results.
Is it safe to create a custom tag like "prodcolor" with any non-reserved nametag or is there a smarter way to achieve this?
Many thanks once again.

You can use HTML5 data- attributes, which is invented for this very purpose. More importantly, the values of the data- attributes can be accessed using JS.
Since you want to include colour, you can use the data-colour attribute, for example:
<option name='6' value="30.95" data-colour="orange">6 Orange(30.95$/month)</option>
<option name='6' value="33.95" data-colour="green">6 Green(33.95$/month)</option>
<option name='10' value="32.95" data-colour="orange">10 Orange(32.95$/month)</option>
<option name='10' value="35.95" data-colour="green">10 Green(35.95$/month)</option>
Even better: Actually, you shouldn't even use the name attribute to store your quantity. Why not use data-quantity instead? :)
<option data-quantity="6" value="30.95" data-colour="orange">6 Orange(30.95$/month)</option>
<option data-quantity="6" value="33.95" data-colour="green">6 Green(33.95$/month)</option>
<option data-quantity="10" value="32.95" data-colour="orange">10 Orange(32.95$/month)</option>
<option data-quantity="10" value="35.95" data-colour="green">10 Green(35.95$/month)</option>
Some background:
There's a nice guide published by Mozilla on how to use JS to access such attributes. Note that it is recommended to use dash (-) separated attributes, instead of any other naming convention, e.g. data-product-name instead of data-productName. This is because the .dataset method in JS converts dash-separated data attributes into camelCase. So data-product-name will be accessible via .dataset.productName, for example.
jQuery also allows you to access the values of data- attributes via the .attr() or .data() methods. The only difference is that:
.attr() is not cached, so you can use it to access dynamically-modified data- attributes, while .data only reads data attributes at runtime.
.attr() can be used to read and write data attributes, but .data() can only be used to read data attributes from the DOM. .data() is also used to access the jQuery data object that is not written to the DOM.
Usage example:
Using your code above, we can create a simple example of alerting the colour of the product upon the firing of the change event:
$(function() {
$('select').change(function() {
var $choice = $(this).find('option:selected')
alert('Colour: ' + $choice.attr('data-colour') + '\n' + 'Price: $' + $choice.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option name='6' value="30.95" data-colour="orange">6 Orange(30.95$/month)</option>
<option name='6' value="33.95" data-colour="green">6 Green(33.95$/month)</option>
<option name='10' value="32.95" data-colour="orange">10 Orange(32.95$/month)</option>
<option name='10' value="35.95" data-colour="green">10 Green(35.95$/month)</option>
</select>

Related

How to send string with quotation marks to controller with Ajax? [duplicate]

I have a drop down on a web page which is breaking when the value string contains a quote.
The value is "asd, but in the DOM it always appears as an empty string.
I have tried every way I know to escape the string properly, but to no avail.
<option value=""asd">test</option>
<option value="\"asd">test</option>
<option value=""asd">test</option>
<option value=""asd">test</option>
How do I render this on the page so the postback message contains the correct value?
" is the correct way, the third of your tests:
<option value=""asd">test</option>
You can see this working below, or on jsFiddle.
alert($("option")[0].value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value=""asd">Test</option>
</select>
Alternatively, you can delimit the attribute value with single quotes:
<option value='"asd'>test</option>
If you are using PHP, try calling htmlentities or htmlspecialchars function.
Per HTML syntax, and even HTML5, the following are all valid options:
<option value=""asd">test</option>
<option value=""asd">test</option>
<option value='"asd'>test</option>
<option value='"asd'>test</option>
<option value='"asd'>test</option>
<option value="asd>test</option>
<option value="asd>test</option>
Note that if you are using XML syntax the quotes (single or double) are required.
Here's a jsfiddle showing all of the above working.
Another option is replacing double quotes with single quotes if you don't mind whatever it is. But I don't mention this one:
<option value='"asd'>test</option>
I mention this one:
<option value="'asd">test</option>
In my case I used this solution.
If you are using JavaScript and Lodash, then you can use _.escape(), which escapes ", ', <, >, and &.
You really should only allow untrusted data into a whitelist of good attributes like: align, alink, alt, bgcolor, border, cellpadding, cellspacing, class, color, cols, colspan, coords, dir, face, height, hspace, ismap, lang, marginheight, marginwidth, multiple, nohref, noresize, noshade, nowrap, ref, rel, rev, rows, rowspan, scrolling, shape, span, summary, tabindex, title, usemap, valign, value, vlink, vspace, width
You really want to keep untrusted data out of javascript handlers as well as id or name attributes (they can clobber other elements in the DOM).
Also, if you are putting untrusted data into a SRC or HREF attribute, then its really a untrusted URL so you should validate the URL, make sure its NOT a javascript: URL, and then HTML entity encode.
More details on all of there here: https://www.owasp.org/index.php/Abridged_XSS_Prevention_Cheat_Sheet

jQuery: get value from different select tag with same name

I was trying to get the value from different select tag with the same name using jQuery.
The following is the HTML
<div class="row">
<div class="col-md-3">
<h1><i class="fa fa-glass" aria-hidden="true"></i></h1>
<select class="form-control SelectWine" id="SelectWine" name="SelectWine[]">
<option value="1">Red</option> <option value="2">Green</option> <option value="3">White</option> </select>
</div>
<div class="col-md-3">
<h1><i class="fa fa-glass" aria-hidden="true"></i></h1>
<select class="form-control SelectWine" id="SelectWine" name="SelectWine[]">
<option value="1">Red</option> <option value="2">Green</option> <option value="3">White</option> </select>
</div>
</div>
The following is how I am accessing in jQuery:
$('.SelectWine').each(function (index){
var wineId=[];
wineId.push($(this).val());
console.log('Wid',wineId[0]);
console.log('Wid',wineId[1]);
console.log('Wid',wineId[2]);
});
I am getting console log as following
Wid 1
Wid undefined
Wid undefined
Wid 3
Wid undefined
Wid undefined
I'm guessing each time it's overriding the value. But i need to store the values from each select tag in to one array.
Note: the first select tag is in the default(index 1) and second one i selected the third option(index 3).
This code is to get the users input for 2 or 3 different products and store it into the cookie for further use, but first i need to store it as array then i am able to store as json array in the cookie.
I tried accessing through the name of the element but it's only responding for accessing using the id.
I was trying for hours, can't figure out a way. your help will be great !!
You need to declare the array outside the loop, otherwise you are creating a new array in each iteration and don't have access to it outside of the each callback due to scope.
var wineId=[];
$('.SelectWine').each(function (index){
//now each iteration will push to same array
....
When you need to generate an array like this you can use map()
var windeId = $('.SelectWine').map(function(){
return this.value;
}).get();
The main problem is that you are declaring your array inside the for each, so it is getting overwritten. Declare it outside the loop.
Also, unrelated to your problem:
Your select elements have the same name and id. They can and should share a class name, but not element name and id.
You can just use 'this.value' rather than '$(this).val()'. Avoiding the unnecessary use of jQuery when possible will improve performance.
https://jsfiddle.net/1ok6ymgf/
var wineId=[];
$('.SelectWine').each(function (index) {
wineId.push(this.value);
console.log('Wid',wineId[0]);
console.log('Wid',wineId[1]);
console.log('Wid',wineId[2]);
});
Have the ids different and call in javascript using $('#id_name') or Have the class names same and call in javascript using $('.class_name')

Can I use html5 data attribute in HTML select box element?

Any idea can I use .data attribute in HTML select box?I red HTML5 documents but I didn't find any information that could help me.
Is it legal:
<span>Select depatament</span>
<span>
<select id="department" onchange="EnableSelectBox(this)" data-spacing="10cm">
<option selected disabled>-Select-</option>
</select>
</span>
Yes it fine to use data in Html5 tag. I don't know why you want to use in such a way, but you can use it.
for example like this
$(document).ready(function() {
alert($('#department').data('spacing'));
});
jsfiddle link
Using data attributes
Any attribute on any element whose attribute name starts with data- is a data attribute.
To answer the question: Yes. You can use data attributes on any element.
It works fine. Test in JS using:
alert(document.getElementById("department").getAttribute("data-spacing"))

AngularJS Select element set the selected index

So i'm using angular and this is my select html:
<select id="date" ng-model="selectedDay" ng-change="setDate()" >
<option>another option</option>
<option>an option</option>
</select>
this is in my controller:
$scope.selectedDay;
document.getElementById("date").selectedIndex = "0";
The result: Three options: one blank (which is default selected) and then the two options I made in html
What the hell? why isn't the default when i open the view "another option"
Firstly, always check the official documentation. AngularJs is well documented.
Secondly, do not use document.getElementById ("date") selectedIndex = "0" - that's javascript. Avoid using pure Javascript when an Angular function is available.
Documentation:
https://docs.angularjs.org/api/ng/directive/select
https://docs.angularjs.org/api/ng/directive/ngSelected

Converting escaped text to html in javascript?

I used $.get and received data like
'<option value=\"US-ID\" >Idaho<\/option>\n <option value=\"US-IL\" >Illinois<\/option>\n <option value=\"US-IN\" >Indiana<\/option>\n <option value=\"US-KS\" >Kansas<\/option>\n'
I want to use $(...).html(html_data) how do I make the data I get into html data that I can use?
what I'm getting when $(...).html(data)
http://jsfiddle.net/9WeUv/
Don't know if this matters, but console.log(data):
'...data...'
whereas console.log('regular_string'):
regular_string // no quotes
What's wrong with:
var html_data = '<option value=\"US-ID\" >Idaho<\/option>\n <option value=\"US-IL\" >Illinois<\/option>\n <option value=\"US-IN\" >Indiana<\/option>\n <option value=\"US-KS\" >Kansas<\/option>\n';
$('#select_element_id').html(html_data);
http://jsfiddle.net/45CYX/
After your edit:
Sorry, isn't the string you've received the one you wrote on top? In your jsFiddle you do not have any JS code, just some text in a select tag - which is not what you are saying in the question.
Assuming you grabbed the html from an ajax call and want to add it to the body.
$newSelect = $("<select></select>").html(html_data);
$(document.body).append($newSelect);
http://api.jquery.com/jQuery/#jQuery2 - Creates DOM elements on the fly from the provided string of raw HTML.

Categories