logo
down
shadow

JS: Keep variable values for onclick event attached inside for loop


JS: Keep variable values for onclick event attached inside for loop

By : user3045440
Date : December 02 2020, 10:46 PM
This might help you You must scope your variables declaring it by the use of let, that way you'll scope it exclusively for that iteration. Avoid to declare a variable like i = 0, bacause that way you create a global variable and it will not work (throw an error) on 'use strict' cases.
code :
let Columns = 3
let rows = 3
const table = document.getElementById("table")

for (let i = 0; i < rows; i++) {  
  let row = document.createElement("tr");
  row.textContent = "row " + i;
  table.appendChild(row)
  for (let j = 0; j < Columns; j++) {
      var col = document.createElement("td")
      row.appendChild(col)
      col.id = i + "" + j;
      col.onclick = function() {
          console.clear()
          console.log(i, j)
      }    
  }
}
tr, td{
  border: 1px solid;
  min-height: 60px;
  min-width: 60px;  
}
<table id="table"></table>
var Columns = 3
var rows = 3
var table = document.getElementById("table")

for (var i = 0; i < rows; i++) {  
  var row = document.createElement("tr");
  row.textContent = "row " + i;
  table.appendChild(row)
  for (var j = 0; j < Columns; j++) {
      var col = document.createElement("td")
      row.appendChild(col)
      col.id = i + "" + j;
      col.onclick = function(rowI, colJ) {
          console.clear()
          console.log(rowI, colJ)
      }.bind(this, i, j) //bind parameters -> this is the context
  }
}
tr, td{
  border: 1px solid;
  min-height: 60px;
  min-width: 60px;  
}
<table id="table"></table>


Share : facebook icon twitter icon
dynamic button onclick event inside for loop

dynamic button onclick event inside for loop


By : Ridovan
Date : March 29 2020, 07:55 AM
will help you i'm using this code to create dynamic buttons within for loop.. , create an arraay of buttons...
code :
Button[] buttons=new Button[10];
Button button = new Button(this);
 button[i] = new Button(this);
    button[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
        //your onclicklistener code
}
onclick event inside table and foreach loop

onclick event inside table and foreach loop


By : Piyush Singh
Date : March 29 2020, 07:55 AM
it fixes the issue As I understand your question you want fetch click on every row. then your code should be as:
Your Script should be out side
code :
<script type="text/javascript">
  function newDoc(id) {
     window.location.assign("<?php echo base_url();?>/read_messages/"+id);
  }
</script>


<?php foreach ($messages->result() as $row)
      { 
                echo "<tr onclick='newDoc(".$row->id.")'>";
                echo "<td>".$row->author. "</td>";
                echo "<td>".$row->posted_in. "</td>";
                echo "<td>".$row->title. "</td>";
                echo "<td>".$row->body. "</td>";

                echo "</tr>";   
      }
?>    
Ajax changing onclick event image inside the loop

Ajax changing onclick event image inside the loop


By : Allan
Date : March 29 2020, 07:55 AM
help you fix your problem Are you sure there is only one li[aria-hidden=false] within the entire html?
The correct approach should be like finding the unique element in order to retrieve the properties you want, by specifying the immediate parent() of the element, for e.g.
code :
$('#dashboard').on("click", 'li > a.save', function(){

    // $( this ).parent() is the immediate parent of 'a.save' which is 'li'
    var img_id      = $( this ).parent().find('.mytravel-img-id').val();
    var img_cat     = $( this ).parent().find('.mytravel-img-id').attr('img-cat');
    var curr_data   = $( this ).attr('current-data');
...
Is there a way to access the variable inside the onclick event?

Is there a way to access the variable inside the onclick event?


By : L.Dem
Date : March 29 2020, 07:55 AM
To fix this issue I have this simple onclick eventfunction and i would like to know if it's possible to acces the variable that is inside it and use it outside this function, if not is there a way to do something similar? , You'll have to get a few things correct:
code :
this.count =0;

document.getElementById('myButton').addEventListener('click', function() {
//Access outer variables
this.count++;
document.getElementById('buttonCount').innerHTML = this.count;

//Send something outside 
var innerVariable = 'String from  click handler!!';
this.fromClick(innerVariable);

}.bind(this));

this.fromClick = function (innerVariable) {
 alert(innerVariable);
}
Add variable to onClick() event inside of prepend() method

Add variable to onClick() event inside of prepend() method


By : Bill
Date : March 29 2020, 07:55 AM
it helps some times Instead of trying to add the onclick attribute, it is better practice to bind the event handler via JS code, and that way you will avoid problems with referencing variables:
code :
var link = "https://google.com";
$('#myDiv').prepend($("<input>").attr("type", "checkbox").click(function () {
    document.location.href = link;
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myDiv">
  <p>
  the div
  </p>
</div>
Related Posts Related Posts :
  • redux how to use state
  • All data in the db is lost when closing a express based node js server
  • How to convert javascript code for Angular
  • XPath select on child nodes
  • Idle event on mouse move - how to stop script permanently on mouse move
  • Why do I get logic is not defined in this code
  • When I enter a number in the input, the first function starts
  • ES6 imports and node_modules hell
  • How to get css selector of clicked-on element?
  • How to auto input MySQL data (input column 1 data to auto input column 2 data with same column) in php?
  • Appending to Datalist Via Javascript
  • Customizing Material-UI Components with Styled-Components
  • Populate elements with class name using Javascript
  • How to execute promises in batches (first resolving 10, then next 10 and so on)
  • Maximo JS automation script: "importPackage" is not defined
  • How to surround selected text inside textarea with <em> on key combination CTRL+i?
  • Your configured registry does not support audit requests ~ On npm audit
  • What's the Angular equivalent of Vue <slot/>?
  • Iconify icon not updating when "data-icon" set with setAttribute()
  • Javascript newbie stuck with XMLHttpRequest return data
  • How to add obj to to state in my example Redux React
  • Loading "grunt-karma.js" tasks...ERROR >> SyntaxError: Unexpected identifier
  • Why do I get log is not defined
  • get the multiple index of the same string
  • How can I iterate over an Array object by using For IN or FOR OF
  • Launch local executable from web browser
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • Trying to define a promise.all
  • Python GEE to extract featurecollection timeseries from Landsat imageries
  • How to write negative binary number?
  • Unable to set property of individual object
  • Why Named Function Expression itself cannot assign Name to another Value?
  • How to reset scroll position on single page pagination
  • How to scroll to bottom of page, when a new message is sent - Socket.io
  • How to reconstruct audio blob from a base64 encoded String?
  • How to calculate numbers within an array of objects
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org