call function on button click in handlebars [duplicate] - javascript

This question already has answers here:
How to Pass an Object to client Javascript - NodeJS & express
(2 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I have been tryinng to call a function on button click in handlebars view,
but unable to do so.
Now, I am new to it and maybe somehow missing the obvious. would love some help on this.
basically, it's a table which I am creating dynamically, but unable to call the function on button click.
here's the relevant code inside calendar.hbs
{{#each events}}
<tr>
<td>{{this.subject}}</td>
<td>{{this.start.dateTime}} ({{this.start.timeZone}})</td>
<td>{{this.end.dateTime}} ({{this.end.timeZone}})</td>
<td>
<ul class="list-unstyled">
{{#each this.attendees}}
<li class="border p-1" title="{{this.emailAddress.address}}">
{{this.emailAddress.name}}
</li>
{{/each}}
</ul>
</td>
<td>{{this.location.displayName}}</td>
<td><button onclick="editEvent({{this}})" >Edit</button></td>
</tr>
{{/each}}
</tbody>
and I have put the function in layout.hbs
inside script tag like this
<script>
function editEvent(val){
return function(e){
console.log('val : ',val);
}
}
</script>
but I still get an error saying "Uncaught SyntaxError: Unexpected identifier"
please tell me where am I going wrong.
now, I also tried doing it in app.js like this
hbs.registerHelper("editEvent", function(event) {
console.log('event : ',event);
});
and then used in in calendar.hbs like
Edit
and it was working I could see it in the console. but the problem was that it seemed to be calling the function on load and it kind of was automatically calling the function for all rows of the table on load... which I dont want.
so, what is the best way to do it?
EDIT:
I looked at the html there and it shows up like this
okay, I looked at it and it's showing up as
<td><button onclick="editEvent([object Object])" >Edit</button></td>
not sure how to fix it though.
I am not sure why you marked it as duplicate.
The questions linked to - dont answer the question I have . But if you do feel that my question is answered here, then please at least send me a message with how to fix my problem.

Related

Unable to update element ID of HTML text using Javascript Jquery [duplicate]

This question already has answers here:
jquery executes too fast
(2 answers)
Closed 1 year ago.
Using JS and AJAX, I am loading a template file on my Index.html page.
Once the template is loaded, I then want to apply changes to the DOM.
The template is successfully loading on the index.html page.
The JS is FAILING to update the DOM elements.
What am I doing wrong?
I have 2 html pages.
index.html
page-banner-area.html
index.html
<div id="page-banner-area"></div>
<script>
$(function(){
$("#page-banner-area").load("assets/static_html/page-banner-area.html");
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
</script>
page-banner-area.html
<div class="p-2 flex-grow-1">
<h3><span id="title"></span></h3>
<span id="keypoint-1"></span><br />
<span id="keypoint-2"></span><br />
<span id="keypoint-3"></span>
</div>
The problem is that the load() method is asynchronous, you need to do your changes within a callback method in order for them to be properly applied. See the JQuery docs for more information https://api.jquery.com/load/
As for a solution, you should be doing this instead:
$(function(){
$("#page-banner-area").load("assets/static_html/page-banner-area.html", function() {
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
});
I thinks this can solve your problem!
<div id="page-banner-area"></div>
<script>
$(() => {
$("#page-banner-area")
.load("assets/static_html/page-banner-area.html", () => {
$("#title").text('Join a Community Group in your area.');
$("#keypoint-1").text('We are against mandatory vaccines & passports.');
$("#keypoint-2").text('We do not stand for corruption & censorship.');
$("#keypoint-3").text('We believe in freedom!');
});
});
</script>

JavaScript script to inset data from page to modal [duplicate]

This question already has answers here:
Thymeleaf attribute and modal
(3 answers)
Closed 4 years ago.
I know, that this question was asked many many times, but i try and code not working.
This function must parse data from my
<a id="dep-modal-pic" class="edit_dep modal-trigger" href="#modal3" th:attr="data-dep_id=${department.id}"> and put dep_id to modal input.
var bookId not working. when i give fixed value to this var it is work, but in my thymeleaf template every new field is new value because
<tr th:each="department : ${departments}">
<td class="dep_id" th:text="${department.id}">1</td>
<td th:text="${department.name}"></td>
</tr>
So, please, can you correct my code? I cant sleep, all day making this thing and still not working.
I need value dep_id to modal input
<input id="ids" name="ids" value="" type="text" class="validate">
$('#modal3').click(function(e) {
var bookId = $(e.relatedTarget).data('dep_id');
$(e.currentTarget).find('input[id="ids"]').val(bookId);
});
The click handler should be attached to #dep-modal-pic, something like:
$('#dep-modal-pic").click(...)
Update:
This is a duplicate of Thymeleaf attribute and modal
Please check my answer on the other post which is more clear

Why does JQuery .val() method sometimes return undefined when code is valid? [duplicate]

This question already has answers here:
val() vs. text() for textarea
(2 answers)
Closed 4 years ago.
Not a duplicate question; so please consider the content closely before presumption.
I've been using JQuery for years and have never seen this type of behavior before. Consider the following:
<html>
<div class="order-form-group">
<label class="order-form-label" for="guestSpecialInstructions">Special Instructions:</label>
<textarea class="order-form-textarea" id="guestSpecialInstructions" type="text"></textarea>
</div>
<div class="order-form-group">
<label class="order-form-label" for="guestReason">Reason:</label>
<textarea class="order-form-textarea" id="guestReason" type="text"></textarea>
</div>
<div class="button-container">
<input class="order-form-submit" type="submit" value="Submit">
</div>
</html>
I've observed that the following script in some instances will return 'undefined' even when "all" the more obvious reasons have been eliminated. Such as
having the incorrect selector, having more than 1 id on the page and etc.
<script>
var specInstr = $("#guestSpecialInstructions").val();
var guestReason = $("#guestReason").val();
</script>
I spent literally hours attempting to determine what the disconnect was; stripping my code to the simplest basic level and couldn't find any reasonable explanation for the behavior.
The code is contained within a simple HTML page; nothing fancy and references the JQuery repository https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
I have another project which runs in an aspx page, still the markup is identical and the .val() method works without issue.
After hours of hitting a wall I ran across the post at JQuery: .val() is not working for textarea and someone else attesting to the exact same issue using valid code and the suggestion was:
<script>
var specInstr = $("#guestSpecialInstructions")[0].value;
var guestReason = $("#guestReason")[0].value;
</script>
Then the issue is automagically resolved. Only problem I have with this is that there no one seems to have answered the question of why the JQuery .text() method sometimes return undefined when all aspects of the code is valid.
Resolutions are great but without understanding why the issue exists, really gains nothing intellectually.
If I need to change the wording of the title, let me know.
You can only use text() on a <textarea> if it is pre-populated and to return the original content
Any changes to the content by user or setting new value programatically will not alter what is returned by text() as it will always be the original pre-pre-populated content
Always use val() to get and set
var $txt = $('textarea')
console.log('text() Original content:', $txt.text())
console.log('val() Original content:', $txt.val())
$txt.val( 'Some new content')
console.log('text() after value change:', $txt.text())
console.log('val() after value change:', $txt.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="one" type="text">
Original text
</textarea>

JavaScript span.appendChild() Returns Uncaught TypeError From Console [duplicate]

This question already has answers here:
Selecting element by data attribute with jQuery
(12 answers)
Closed 5 years ago.
I'm sort of a novice with HTML and JavaScript, but I'm running into some trouble with this one.
I have the following code snippet:
<div data-contents="true">
<div class="" data-block="true" data-editor="369vc" data-offset-key="e371k-0-0">
<div data-offset-key="e371k-0-0" class="_1mf _1mj">
<span data-offset-key="e371k-0-0">
<span data-text="true">TEXT HERE</span>
</span>
</div>
</div>
</div>
I'm trying to insert text where the "TEXT HERE" resides using the following commands (as found on this Stack Overflow thread) from within the console:
span = document.getElementById("data-text");
txt = document.createTextNode("TEXT HERE");
span.appendChild(txt);
However, when I run that command, all I get in return is Uncaught TypeError: Cannot read property 'appendChild' of null at <anonymous>:3:6.
I've read it's caused by the element not being defined prior to the script running, so it's unable to assign the text to it. I'm not fully clear on why it wouldn't run even though the website has already loaded though. Any ideas? I'm hoping to eventually hook this to a button that's loaded on the webpage, instead of it automatically running upon load if that makes sense.
NOTE: I'm not creating a website from scratch. This is a script being used on Facebook by TamperMonkey, so I can't permanently load it into the webpage.
You call this:
span = document.getElementById("data-text");
But don't have any id called data-text.
Either change the code to this:
span = document.querySelector("[data-text]");
Or change the html to this:
<span id="data-text" data-text="true">TEXT HERE</span>
Notice the id="data-text" That is what getElementById is looking for.

get table row data on checkbox check

Edit : I would like to rephrase my question
I am simple trying to get anchor tag text inside <td> on checkbox check.
Problem is that anchor tag doesn't have id or class
This is a sample of my table
<table class="wp-list-table widefat fixed striped users">
<tbody id="the-list" data-wp-lists="list:user">
<tr id="user-18">
<th scope="row" class="check-column">
<label class="screen-reader-text" for="user_18">Select abc</label>
<input type="checkbox" name="users[]" id="user_18" class="subscriber" value="18">
</th>
<td class="username column-username has-row-actions column-primary" data-colname="Username">
abc
</td>
</table>
I have searched some post and tried to create some function
<script type ="text/javascript">
$('#changeit').click(function(){
var values = [];
$(".wp-list-table input[name='users[]']:checked").each(function(){
row = $(this).closest("tr");
});
alert($(row).find("a")[0]);
});
</script>
this gave me anchor tag href data, but I need text enclosed in anchor tag.
I tried
alert($(row).find("a")[0].text());
alert($(row).find("a")[0].val());
alert($(row).find("a")[0].val);
But they are not giving me the anchor tag text.
Any suggestion will be helpful.
Try this:
function Bindthis() {
$('#changeit').on('click', function() {
alert('1'); //this is hitting
var values = [];
$('.subscriber').attr('checked', true).each(function() {
alert('2');
row = $(this).closest("tr");
});
});
}
This is easily traceable by following some good coding practices.
First, you need your code well indented. Indentation is a must if you want to write good, clean and error free code. Error free because indentation helps a lot to identify different scopes.
Second, ALWAYS look for logs. I know that you don't look for logs because you use alert() instead of console.log(), and also, if you open the console (F12) with your code, you will notice this error:
Uncaught Error: Syntax error, unrecognized expression: #the-list input[name=users[]]:checked
With this, is easy to understand that the selector syntax is wrong. Searching a bit around internet and learning about selectors, you will notice that the syntax needs some quotes, like this #the-list input[name='users[]']:checked.
Seems that you don't understand well how selectors work, so, to avoid this problem and future ones, I recommend you to read a bit about them. This way you will avoid repeating the same selectors questions here. Here is a good reference website, with an online tester: http://www.w3schools.com/cssref/css_selectors.asp
finally I made this code which is working for me
$(".wp-list-table input[name='users[]']:checked").each(function(){
row = $(this).closest("tr");
anchor = $(this).closest('tr').find("a:first");
});
alert($(anchor).text());

Categories