passing variables into onclick method in html javascript - javascript

Passing variables into onclick method.How do I do it in HTML and javascript
I am passing the variable usersid from the onclick calling funtion to called function.
<tbody>
{% for each_user in detail %}
<tr>
<td>{{ each_user.userss_name }}</td>
<td>{{ each_user.userss_email }}</td>
<td><input class="btn btn-info" type="button" value="Edit" id="edit"
onclick="editUser('\''+ '{{ each_user.userss_id }}' +'\'')"></td>
</tr>
{% endfor %}
</tbody>
My script code is
<script>
function edituser(user_id) {
console.log(user_id);
document.location.href = "/'{{ user_id }}'/user/edit/"
}
</script>
What is the expected result is when I click the edit button it should take me to the url /user_id/user/edit. So user id is the integer here.So I shoule see /1/user/edit.
But what I am getting here is http:/""/interviewer/edit and page not found error also.
So I dont know how to pass the variable to the url.

edit your document.location.href like below should works. The issue is user_id is a javascript variable, not a template variable, so you don't wrap it with {{ }}.
<script>
function edituser(user_id) {
console.log(user_id);
document.location.href = "/" + user_id + "/user/edit/"
}
</script>

<script>
function edituser(user_id) {
console.log(user_id);
document.location.href = "/" + user_id + "/user/edit/"
}
</script>
user_id doesn't need to be in {{}}

Related

JavaScript Uncaught TypeError: Cannot read property 'style' of null: Button Onclick makes html disappear

In a django project, I've set up a JavaScript function to select/block certain pages. I have another JavaScript function for the pages that are being loaded. This function has an onclick event listener that submits text to a form field. The problem I'm having is that when I click a button to add text to a form field, the entire page disappears. Both functions are in a static file called "main.js" The exact error message showing in the console is...
Uncaught TypeError: Cannot read property 'style' of null
at showPage (players:6382)
at HTMLButtonElement.button.onclick (players:6388)
Here's the function controlling showing/blocking of individual pages.
function showPage(page) {
document.querySelectorAll('tbody').forEach(tbody => {tbody.style.display = 'none';})
document.querySelector(`#${page}`).style.display = 'table-row-group'; ---(This line in error message)
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('button').forEach(button => {
button.onclick = function() {
showPage(this.dataset.page); ---(This line in error message)
}
});
});
Here's an example from the html template of a button targeted by this function.
<button class="posbutton" data-page="page1">QB</button>
This is the function that submits text to a form field.
function myFunction(txt) {
var myTxt = txt;
if (txt.includes('QB')) {
document.getElementById("QB_name").value = myTxt;
}
else if (txt.includes('RB')) {
document.getElementById("RB_name").value = myTxt;
}
else if (txt.includes('WR')) {
document.getElementById("WR_name").value = myTxt;
}
else if (txt.includes('TE')) {
document.getElementById("TE_name").value = myTxt;
}
else if (txt.includes('K')) {
document.getElementById("K_name").value = myTxt;
}
}
Here's an example of the html element targetted by the showPage function. It also contains a line with the button that's linked to the myFunction for submitting text.
<tbody id="page1">
{% for q in QBpage %}
<tr>
<th scope="row">
</th>
<td><h6>{{ q.player_name }}</h6></td>
<td><input type="button" class="btn btn-outline-primary btn-sm m-0 waves-effect" onclick="myFunction('{{ player_data.player_name }} {{ player_data.position }}')">Add</input></td>
<td><h6> {{ q.team }} </h6></td>
<td><h6> {{ q.position }} </h6></td>
<td><h6>{{ q.points }}</h6></td>
</tr>
{% endfor %}
</tbody>
Before putting both JavaScript functions into a static file, I experimented with putting the script tags at the start or at the end of the in all manner of combinations. So far, the advice suggested here Why does jQuery or a DOM method such as getElementById not find the element? hasn't been helpful for me. I've tried a lot of the suggestions in the answers there but I'm still having the same problem.
The error
at HTMLButtonElement.button.onclick (main.js:15) still persists which is showPage(this.dataset.page);this line in the showPage function.
I'm really stuck on this. Any advice is greatly appreciated.
document.querySelector('#'+page).style.display = 'table-row-group';
use this

How to pass php parameters inside blade file using AngularJS?

I will try to be as clear as possible. I have a table with ng-repeat in blade file.
I want to send parameters to a Laravel function, inside the repeat loop.
Here is the example:
The angular
app = angular.module("myApp",[], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
The blade file : $idVal needs to be the id from the loop.
<tr ng-repeat="rec in recomends" ng-init="recomends = {{ $recomends }}">
<td ><% $index + 1 %></td>
<td><% rec.name %></td>
<td>{{ HelperAdmin::getTotalParam('quality',$idVal) }}</td>
</tr>
The laravel Function:
public static function getTotalParam($field,$reco_id){
$total = DB::select("SELECT AVG($field) AS mysum FROM recommendation_measure WHERE reco_id = $reco_id ");
return number_format($total[0] ->mysum,2);
}
I need to push $idVal as the id of the loop data. But I can't find a way to send it. Any idea?
Hope this question is clear.

How to pass variable from twig to js?

Code prints out tasks information. I want to pass tasks array to JS. How could I do that? Some of my twig code:
<div>
{% for task in tasks %}
<tr>
<td id>{{ task.Id }}</td>
<td>{{ task.Status }}</td>
<td>{{ task.Name }}</td>
<td>{{ task.Description }}</td>
<td>{{ task.Category }}</td>
<td>{{ task.Author }}</td>
<td>{{ task.CreationDate|date("m/d/Y") }}</td>
<td><a id="myLink" href="/edit/{{ task.ID }}" > Edit </a></td>
<td><a id="myLink" href="/delete/{{ task.ID }}" >Delete</a></td>
<?php echo 2+2; ?> </tr>
{% endfor %}
</table>
</div>
I want to pass array to this js class:
$(function(){
$('#calendar').fullCalendar({
});
});
You can serialize the array in json format: {{ tasks | json_encode() }}.
If your javascript is inside a <script> element of the twig template, you can just do: var data = {{ tasks | json_encode() }}.
Otherwise, you can put the serialized array somewhere in the twig template as an element's attribute:
<div id="data-element" data-tasks="{{ tasks | json_encode() }}">.
Then just get the data with
var jsonString = $('#data-element').data('tasks');
var data = JSON.parse(jsonString);
First of all , you need to know that there are a big deference between PHP arrays and Javascript arrays.
you need to convert your array to a common understood format that both PHP and Javascript can understand , which is JSON .
so I will assume that you are sending your tasks from your controller to twig as a json format, then you can set your javascript variable as follows :
<script>
var tasks = '{{ tasks }}';
var tasksObj = JSON.parse(tasks); // to convert json into a javascript object
</script>

Django : How to give parameters to {% url %} tag in javascript function which will be used in FOR loop?

I try to make a button with a javascript "location.href" property in Django ListView templates.
{% for item in object_list %}
<div class="clear_float">
<h2>{{ item.title }}</h2>
 <b><i>{{ item.description }}</i></b>
<p style="display:inline" class="editbutton">
<b><button onclick="photoAdd()">Add Photo</button></b>
{% if item.author == request.user %}
<b><button onclick="albumEdit()">Edit</button></b>
<b><button onclick="albumDelete()">Delete</button></b>
{% endif %}
</p>
</div>
{% endfor %}
And albumEdit() and albumDelete() is coded like below.
function albumEdit(){
location.href="{% url 'photo:album_edit' object.id %}";
}
function albumDelete(){
location.href="{% url 'photo:album_delete' object.id %}";
}
{% url 'photo:album_edit' object.id %} returns "photo/object.id/edit/"
The problem is, I guess, the ListView returns object_list so the javascript function is used in FOR loop with item object.
I tried replacing object.id with item.id but it didn't work.
So I also tried another way to give a argument to javascript function like below.
<b><button onclick="albumEdit({% url 'photo:album_update' item.id %})">Edit</button></b>
and javascript
function albumEdit(arg){
var address = arg;
location.href=encodeURI(address);
}
Cuz I don't know much about javascript, it also didn't work.
I will be grateful for any advice and help.
Thank you :D
I fixed it with input javascript code to the onclick attribute like
<b><button onclick="location.href='{% url 'photo:album_edit' item.id %}'">Edit</button></b>
You can pass a parameter in your js onclick function:
<button onclick="albumEdit({{ url 'photo:album_edit' item.id }})">Edit</button>
and use it to make the redirection:
function albumEdit(href_url){
location.href=href_url;
}

Go to URL with ID onClick() Using Laravel

I am building a simple contact database with Laravel and a MySQL database. I have a basic HTML file with a data table that list a series of records. I would like to make it so that when I click on a row, I go to a page based on the ID number of the record in the row clicked.
I have the table populated using a #foreach loop as such:
<tbody>
#foreach ($people as $person)
<tr>
<td>
<a>{!! link_to_action('ContactController#show', $person->id, $person->id) !!}</a>
</td>
<td>{{ $person->name_first }}</td>
<td>{{ $person->name_middle }}</td>
<td>{{ $person->name_last }}</td>
</tr>
#endforeach
</tbody>
The controller (ContactController) shows this:
public function show($id)
{
$person = Contact::findOrFail($id);
return view('contacts.show', compact('person'));
}
Now, I have a JavaScript script on the page:
<script type="text/javascript">
$(document).ready(function() {
$('#contacts').dataTable();
$('#contacts tbody').on('click', 'tr', function () {
var name = $('td', this).eq(1).text();
alert( 'You clicked on '+name+'\'s row' );
window.location="";
} );
} );
</script>
I assume I only need to insert the proper link in:
window.location="";
How do I write the link? I tried writing a number of variations with the Laravel syntax, where I need to access a route in my ContactController that would go to contacts/{id}. I tried:
window.location="{{URL::to('contacts', $person->id)}}";
That doesn't work. Please let me know what link to use in order to go to contacts/1 or contacts2, for example.
try this.
$('#contacts tbody').on('click', 'tr', function () {
var name = $('td', this).eq(1).text();
var link = $('td', this).eq(0).find('a');
alert('You clicked on ' + name + '\'s row');
window.location=link.attr('href');
});
And the show method only accepts one argument.
<td>
{!! link_to_action('ContactController#show', $person->id) !!}
</td>
And no need to wrap it in "a" tags
Add your link to a data attribute on your tr element and then use it in your JavaScript.
HTML:
<tbody>
#foreach ($people as $person)
<tr data-link='{{ action('ContactController#show', $person->id) }}'>
<td>
<a>{!! link_to_action('ContactController#show', $person->id, $person->id) !!}</a>
</td>
<td>{{ $person->name_first }}</td>
<td>{{ $person->name_middle }}</td>
<td>{{ $person->name_last }}</td>
</tr>
#endforeach
</tbody>
JavaScript:
$('#contacts tbody').on('click', 'tr', function () {
var name = $('td', this).eq(1).text();
alert( 'You clicked on '+name+'\'s row' );
window.location = this.getAttribute('data-link');
} );

Categories

Resources