Why can't I access a jquery select val here? - javascript

I have a simple html select as so:
<select id="eventid">
<option value="a">a</option>
<option value="b">b</option>
</select>
The script im using is using this code where I have to grab the select value.
<script id="template-upload" type="text/x-tmpl">
<tr class="template-upload fade">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<td class="post"><label><input type="hidden" name="userid[]" value="$( "#eventid" ).val()" required></label></td>
I think it isn't working because of the x-tmpl script header but I have to use that. How can I grab the select value inside this tmpl script?
Thanks

That's a quote mismatch, change :
value="$( "#eventid" ).val()"
to
value="$('#eventid').val()"
and hopefully whatever strange templating system you're using lets you use jQuery directly in value attributes ?

Javascript isn't executed in value attributes. It's only executed in onXXX attributes, and in href when the URI scheme begins with javascript:.
You should use an onsubmit handler for the form that copies the select value into the form field.

Related

How to access the javascript variable inside html tags

I wanted to added javascript variable inside html code.
Here is my code:
<select id="currentrun" name="currentrun" >
<option value=""><script>selectedrun</script></option>
</select>
and my js function
var currentrun="";
var selectedrun="";
function setCurrentRun()
{
currentrun = document.getElementById("runlist");
selectedrun = currentrun.options[currentrun.selectedIndex].value;
}
But this doesn't work.
Can anyone help me to do this.
Thanks in advance.
You don't have to run the script like that.
The value of the currentrun can be retrieved as:
document.getElementById('currentrun').value
And for completeness, if you want to trigger a JavaScript function call each time the selection is modified, do this:
<select onchange="my_function();">
<option>...</option>
</select>
It seems like you are trying to set the text of the option element with javascript. Here is one way you can do it using the id of the element to get it and then set the text property of the element to your javascript variable:
<select id="currentrun" name="currentrun" >
<option id="currentoption" value=""></option>
</select>
<script>
document.getElementById("currentoption").text = selectedrun;
</script>
Be sure to put any necessary javascript that declares and sets the selectedrun variable before the above script.

custom tag containing data in option

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>

How to change name and id of element using jQuery?

I'm new at jQuery. I'm cloning one specific HTML block and trying to change last cloned html's element's nameor id, class but i couldn't. I can find and alert name of element that i want to change, but i can not change it. Hope you can help me.. thanks in advance.
My code
jQuery(document).on("click",".smclass",function(){
var html = jQuery(this).closest(".entry-edit").clone().appendTo(".main-col-inner").html();
html = jQuery(html).find('.start').attr('name','optional[2][type]').attr('id', 'Type1');
}
HTML
<div class="entry-edit">
<!-- html codes -->
<button id="Addfield" title="Field Ekle" type="button" class="smclass" onclick="" style="float: right;"><span><span><span>Field Ekle</span></span></span></button>
<!-- html codes -->
<select id="Type" name="optional[1][type]" class="start">
<option value="0">Date</option>
<option value="1">Text</option>
<option value="2">Select</option>
</select>
<!-- html codes -->
</div>
Your code is just putting an html string into a variable and then creating a new jQuery object with said html. You are not selecting the new element and changing it
//Just remove the .html() call and you will have the cloned element
var ele = jQuery(this).closest(".entry-edit").clone().appendTo(".main-col-inner");
ele.find('.start').attr('name','optional[2][type]').attr('id', 'Type1');
You also do not need to make multiple .attr calls, you can pass it an object with the name value pairs you want to set
ele.find(".start").attr({
"name":"optional[2][type]",
"id":"Type1"
});
just try vise versa
var clonedObject = jQuery(this).closest(".entry-edit").clone();
clonedObject .find('.start').attr('name','optional[2][type]').attr('id', 'Type1');
clonedObject.appendTo(".main-col-inner").html();

Get text inside HTML comment tag?

I have the following HTML:
<!--
<option value="HVAC">HVAC</option>
<option value="Cooling">|---Cooling</option>
<option value="Heating">|---Heating</option>
-->
....
I fetch this file dynamically using jQuery's get method and store it in a string variable named load_types.
How can I strip the HTML comment tags and everything outside of them? I only want the inside HTML:
<option value="HVAC">HVAC</option>
<option value="Cooling">|---Cooling</option>
<option value="Heating">|---Heating</option>
I tried to use the solutions here but nothing worked properly--I just get null as a match.
Thanks for the help!
Please never use regex to parse HTML. You can use the following instead:
var div = $("<div>").html(load_types),
comment = div.contents().filter(function() {
return this.nodeType === 8;
}).get(0);
console.log(comment.nodeValue);
DEMO: http://jsfiddle.net/HHtW7/
You can simply get the html of the parent tag where the comment is and do a .replace("<!--","").replace("-->", "") which will simply remove the comment tags and then append this markup to some other parent or replace your current markup or create a new parent for it and append it.
This will allow you to use the jQuery selectors to retrieve the required data.
var comment = '<!-- <option value="HVAC">HVAC</option> <option value="Cooling">|---Cooling</option> <option value="Heating">|---Heating</option> --> ';
jQuery("#juni").append("<select>"+comment.replace("<!--", "").replace("-->", "") + "</select>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="juni"></div>

django template: get dictionary's value based on the key that equals to certain tag's value

I'm very new to web development and I know this might be stupid approach but cannot think of a better way of doing this. In the views.py a method returns a dictionary named sniffer_aps to the template in following format:
sniffer_aps = {device1:[ap1, ap2], device2:[ap3, ap4, ap5], ......}
In the template I have a dropdown list that lists all devices(device1, device2, ......).
In another field I list all aps belong to the device selected in the dropdown list. I want to dynamically adjust the field according to the device I selected, but it doesn't really work.
The dropdown list code is:
<select onchange="refresh(this.value)" id="sniffer_list">
{% for sniffer_ap in sniffer_aps %}
<option value={{ sniffer_ap }}>{{ sniffer_ap.plug_ip }}</option>
{% endfor %}
</select>
My question is that how can I loop though the value in the field that shows aps based on the option selected in the dropdown list?
Right now my approach is to use javascript to detect the "onchange" event of the dropdown list, and change the value the field that list all aps accordingly, then just get the value of the field and treat it as the key of the dictionary.
function refresh(key) {
$('.router').attr('value') = key;
}
For the field that lists aps, it is where the problem is. I'm trying to achieve something like this:
<select multiple="multiple" size="6">
{% for router in sniffer_aps[this.value] %}
<option class="router" value="">{{ router }}</option>
{% endfor %}
</select>
Please correct my approach, or if somebody can provide a better way. Thanks very much.
You're running into trouble here because you're confusing server-side code (Django's templating engine) with client-side code (the Javascript code you're using for the onchange handler). Your server-side code will have run on the server before the resulting HTML is ever delivered to the client, so you can't have any interactions between client-side Javascript and the template logic.
You're right to use Javascript and the onchange event to update the values in the field that lists apps - you could do this on the server, by submitting the form and changing the HTML with Django when the new request is returned, but this takes a new webpage load and isn't nearly as fast or user-friendly as doing it with Javascript.
I would approach this by:
Converting the dictionary to JSON in your Django view class:
import json
...
sniffer_app_json = json.dumps(sniffer_apps)
Outputing the JSON as a JavaScript object in your template code:
var snifferApps = {{ sniffer_apps_json }};
Using JavaScript to update the apps field, using this data. There are many questions addressing this on StackOverflow - you might consider using jQuery, as it makes this sort of manipulation much easier.

Categories