jQuery and jinja2 .data("") returning undefined - javascript

the no of items are displayed along with an edit button with each item on clicking edit button the data of button is retrieved in jQuery function but I am getting undefined not the data-id
<div>
{% for stock in part_temp.part_stock_set.all %}
{% with id="list"|concatenate:stock.id btn_id="btn"|concatenate:stock.id %}
<div id="{{ id }}">
{{ stock.entry_date}}
{{ stock.supplier }}
{{ stock.amount }}
{{ stock.remaining }}
<button id="{{ btn_id }}" type="submit" data-id="{{stock.id}}" onclick="display_popup()" style="position: absolute; right:0;" >edit</button>
<hr>
</div>
<br>
{% endwith %}
{% endfor %}
</div>
instead of {{stock.id}} I also tried passing other string but still got undefined
<script type="text/javascript">
function display_popup() {
var name = $(this).data("id");
window.alert(name);
}
</script>
instead of .data() also tried other like .text() .Val but got nothing

As of current code; this in the display_popup function refers to window object thus its not returning the desired value.
Pass current element context this in the inline click handler
<button onclick="display_popup(this)">
Script, Accept it as parameter and use it to get data
function display_popup(elem) {
var name = $(elem).data("id");
window.alert(name);
}
However, I would recommend you to use unobtrusive event handler. Assign a common class to button.
<button class="edit" data-id="{{stock.id}}" >edit</button>
script
$(function(){
$('.edit').on('click', display_popup); //this will set as context so you existing method will work
});
$(function() {
$('.edit').on('click', display_popup); //this will set as context so you existing method will work
function display_popup() {
var name = $(this).data("id");
window.alert(name);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="edit" type="submit" data-id="1">edit</button>
Set the context of function with current element using .bind()
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
function display_popup() {
var name = $(this).data("id");
window.alert(name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button type="submit" data-id="1" onclick="display_popup.bind(this)()">edit</button>

first, inspect the elements and functions. Try to inspect the HTML and see if the data you need has value. Try to console.log(this) on display_popup function, You should see the button.
If everything is ok, then try to use $(this).data(). It will returns a object with all the data of the element.
If it didn't work (or this case is better for you), use:
$(this).attr('data-id')
this will return the data-id attribute value.
If none of this works, check your jquery version, but i belive the attr will work fine.
----EDIT----
this is undefined on the display_popup function. you need to use onclick="display_popup(this)" and then use the parameter to get the element attributes

Related

alert value of button by onClick

I have a page with a lots of buttons from PHP output with each buttons having different values:
<button class='add' value=".$row['cat_no']." onClick='addItem(value)'>Add To Cart</button>
$row['cat_no'] is data from mysql.
I want to check the button's value when I click it, so I use native JS below:
<script>
function addItem(value) {
alert("this.value");}
</script>
It is not working...it just return this.value. In this case I don't think it is suitable to assign Id to getElementbyId, Pls help to check my mistake or suggest solution. Thanks.
Pls: I dont want to use JQUERY, just native JS.
Use alert(elmt.value); like below. you should pass this to the function
<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>
<script>
function addItem(elmt) {
alert(elmt.value);
}
</script>
the code below helps you retrieve the value of the element that triggered the event:
<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>
<script>
function addItem(sender) {
alert(sender.value);
}
</script>
However, this is filled with code smells.
I would suggest doing the code below
<button id='add-to-cart' class='add' value="test value">Add To Cart</button>
On a separate JS file:
(function() {
function _onLoad() {
var addToCartButton = document.getElementById("add-to-cart");
addToCartButton.addEventListener("click", _onAddToCartClicked);
}
function _onAddToCartClicked() {
var sender = this;
alert(sender.value);
}
document.addEventListener("DOMContentLoaded", _onLoad, false);
})();
This approach ensures that:
Concerns are separated between HTML and JS
External JavaScript file would be cached which results to faster page load time.
UI would render faster since there are no inline scripts
Global namespace won't be polluted
You don't really need this in your function, just use value. And also remove double quotes, because you need to alert function's parameter, not string, like this:
function addItem(value) {
alert(value);
}
Here is the working example:
function addItem(value) {
alert(value);
}
<button class='add' value="yourValue" onClick='addItem(value)'>Add To Cart</button>
Or you can pass the element to function using this, and then get the needed attribute value from addItem method:
function addItem(item) {
alert(item.value);
}
<button class='add' value="yourValue" onClick='addItem(this)'>Add To Cart</button>

Octobercms Component Twig

Can someone show me how to set unique Id for components?
I only know I have to put this code in my default.htm
{% set uid = '{{__SELF__.id}}' %}
how to use it in javascript?
and what is this for?
var avatar_{{uid}} = {{ avatar }};
for example this is my js
$(function(){
$("#tab-close").click(function() {
$("#tab").addClass("hidden");
});
});
How do I set a unique Id for it so that when I duplicate the component both can still work normally without errors?
It might be better to encapsulate your control with a single identifier, like this
<div id="mycontrol{{ __SELF__.id }}">
...
</div>
Then in JavaScript, you can target elements inside:
function initTabs(controlEl) {
var $control = $(controlEl)
$(".tab-close", $control).click(function() {
$(".tab", $control).addClass("hidden");
});
}
The code above targets the class names found only inside the $control container. You would call this function from the markup like so
<script>
$(function(){
initTabs('#mycontrol{{ __SELF__.id }}');
});
</script>

How to pass AngularJS ng-repeat Variable to Javascript click event

I would like to know how to pass Angular ng-repeat variable to my Javascript onclick event
My angular repeater
<div class="data" data-ng-repeat="sub in subs" >
<button onclick="ConfirmDialog(sub.SubID)">Cancel</button>
{{ sub.someOtherProperty}}
{{ sub.someOtherProperty}}
{{ sub.someOtherProperty}}
</div>
My script function
<script type='text/javascript'>
function ConfirmDialog(subID) {
console.log('Succesfully submitted id: ', subID);
});
</script>
The error : sub is not defined (in the onclick() call from the button element) all other properties show as expected.
You are running straight javascript onclick instead of ng-click.
move confirmDialog into your controller and ng-click can attach to it.
<div class="data" data-ng-repeat="sub in subs" >
<button ng-click="ConfirmDialog(sub.SubID)">Cancel</button>
</div>
$scope.ConfirmDialog = function (subID) {
console.log('Succesfully submitted id: ', subID);
});
If you don't want to use ng-click, you still have a chance! Try the following
<tr ng-repeat="supplier in suppliers" id="{{supplier.id}}">
<button onclick="readVariable(this);">
</tr>
<script>
function readVariable(elem){
id = elem.parentNode.id;
console.log(id); //it works!
}
</script>
You should use ng-click instead in order to access the ng-repeat variable
<button ng-click="ConfirmDialog(sub.SubID)">Cancel</button>

A better way to pull an ID from a form submission Javascript/Django

Currently what I have coded up works, but it seems rather crude. Basically here's what I have (simplified):
JQuery ready:
<script type="text/javascript">
$(document).ready(function() {
$('div.partDelete').click(function() {
// TODO this seems like a dirty hack
var split = this.id.split('_');
if(split.length == 3) {
$('#part_id').val(split[0]);
alert($('#part_id').val());
$('#removePartForm').submit();
} else {
alert('There was a problem removing the selected part');
}
});
</script>
The form I am using:
<form id="removePartForm" action="{% url remove_part %}" method="post">
<input type="hidden" id="part_id" name="part_id" value="-1" />
{% for part in current_build.parts.all %}
<div id="{{ part.id }}_part_id" class="partDelete">remove</div>
{% endfor %}
</form>
All I'm trying to do is set the hidden input to take the part.id that has been selected by the user so that I can use it in my views.
For all I know this is the correct way to go about this, but I just have a feeling it isn't. I am new to Django & JQuery so there may be some built in functionality for this that I haven't found yet.
Thanks for any suggestions that you may have!
Solution (see mikaelb's answer below)
Javascript:
$('div.partDelete').click(function() {
var selected_id =$(this).data("id");
$('#part_id').val(selected_id);
$('#removePartForm').submit();
});
HTML changes:
<div class="partDelete" data-id="{{ part.id }}">remove</div>
First of all; IDs shouldn't start with a number (http://www.w3.org/TR/html4/types.html#type-name).
Aside from that, you'd typically use the data-* attribute for setting IDs to communicate with JS from server side. The data-* attribute can be anything you want. So data-foo="" is a valid attribute.
Example:
HTML:
<div class="item" data-id="{{ part.id }}">
<p>Foo</p>
</div>
Javascript:
$(function () { // same as document read
$(".button-class").on("click", function () {
// Here "this" will be the element
var id = $(this).data("id"); // same as getting attribute data-id
// Could also use $(this).attr("data-id")
});
});
Hope this helps.
Edit: Moved comment to make it more clear, changed the example to be more specific to OP's problem.

How can I get the data-id attribute?

I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.
$("#list li").on('click', function() {
// ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);
alert($(this).attr("#data-id"));
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />
</a>
</li>
</ul>
To get the contents of the attribute data-id (like in <a data-id="123">link</a>) you have to use
$(this).attr("data-id") // will return the string "123"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the number 123
and the part after data- must be lowercase, e.g. data-idNum will not work, but data-idnum will.
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
OR
// If you updated the value, you will need to use below code to fetch new value
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).attr('data-fruit','7');
Read this documentation
Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will not be reflected in the data() jQuery function. You have to adjust it via data() function as well.
<a data-id="123">link</a>
JavaScript:
$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321
If you are not concerned about old Internet Explorer browsers, you can also use HTML5 dataset API.
HTML
<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>
JavaScript
var myDiv = document.querySelector('#my-div');
myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"
Demo: http://html5demos.com/dataset
Full browser support list: http://caniuse.com/#feat=dataset
You can also use:
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
This piece of code will return the value of the data attributes. For example: data-id, data-time, data-name, etc.
I have shown it for the id:
Click
JavaScript: Get the value of the data-id -> a1
$(this).data("id");
JQuery: This will change the data-id -> a2
$(this).data("id", "a2");
JQuery: Get the value of the data-id -> a2
$(this).data("id");
HTML
<span id="spanTest" data-value="50">test</span>
JavaScript
$(this).data().value;
or
$("span#spanTest").data().value;
ANS: 50
Accessing the data attribute with its own id is a bit easy for me.
$("#Id").data("attribute");
function myFunction(){
alert($("#button1").data("sample-id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
var id = $(this).dataset.id
works for me!
I use $.data:
//Set value 7 to data-id
$.data(this, 'id', 7);
//Get value from data-id
alert( $(this).data("id") ); // => outputs 7
Using jQuery:
$(".myClass").load(function() {
var myId = $(this).data("id");
$('.myClass').attr('id', myId);
});
Try
this.dataset.id
$("#list li").on('click', function() {
alert( this.dataset.id );
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<ul id="list" class="grid">
<li data-id="id-40" class="win">
<a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">
<img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />
</a>
</li>
</ul>
for pure js
let btn = document.querySelector('.your-btn-class');
btn.addEventListener('click',function(){
console.log(this.getAttribute('data-id'));
})
The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.
$('#select').on('change', function(){
let element = $("#visiabletoID");
element.val($(this).find(':selected').data('record'));
});
For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See .tooltip('dispose').
HTML 5 introduced dataset: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset, the browser compa
But for older browser you can use getAttribute method to get the data-* attributes.
const getDataAttr = (id) => {
if(currentNode.dataset) return currentNode.dataset[id];
return currentNode.getAttribute("data-"+id);
}
The reason to use dataset is constant lookup time, get attribute would not be a constant time lookup, it'll go through all the attributes of the html element and then return the data once it'll find the exact attribute match.
The reason to provide this answer is that nobody mentioned about the browser compatibility and lookup time with the given solution, although both of these solutions are already given by people.
I have a span. I want to take the value of attribute data-txt-lang, which is used defined.
$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});

Categories