Function unable to get called in click event of jQuery - javascript

Unable to access function named print1() in click event of jQuery and it is defined also. I have made a Calculator using jQuery and print1() function prints the value in paragraph tag
$(document).ready(function () {
var temp = 0;
var his1 = "";
var k = false;
//flag=false;
var input = "";
var prev = 0;
var count = 0;
var displayFlag = false;
var divide = true;
var firstNumber = "";
var secondNumber = "";
$(".number").click(function (e) {
var num = $(this).text();
//window.alert(num);
print1(num);
});
function print1(num) {
// code to print here
});
});
https://jsfiddle.net/w2h7zLtn/

Try this script. You need to move the print1 to outside of document ready function
Working link
$(document).ready(function(){
var temp=0;
var his1="";
var k=false;
//flag=false;
var input="";
var prev=0;
var count=0;
var displayFlag=false;
var divide = true;
var firstNumber="";
var secondNumber="";
$(".number").click(function(e){
var num= $(this).text();
//window.alert(num);
print1(num);
});
});
function print1(num)
{
alert(num);
}

I was typing onclick() command code on html page though I had click event in jQuery. Thank you for help !

Related

Javascript a TD click and get row cell data

I have this in Jquery all works:
$(document).ready(function() {
$("#checktable td:nth-child(1)").click(function(event){ // This line I need converted
event.preventDefault();
var $td = $(this).closest('tr').children('td'); //This line I need converted
var tid = $td.eq(0).text();
var tdate = $td.eq(1).text();
var tdescribe = $td.eq(2).text();
var wd = $td.eq(3).text();
var dep = $td.eq(4).text();
// ... more code
I need a similar thing in javascript, above only first td is clicked.
My javascript code so far:
function addRowHandlers() {
var table = document.getElementById("checktable2");
var rows = table.getElementsByTagName('tr');
var tid = '';
var tdate = '';
var tdescribe = '';
var wd = '';
var dep = '';
var tisclr = '';
for (var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].onclick = function() {
tid = table.rows[this.i].cells[0].innerText;
tdate = table.rows[this.i].cells[1].innerHTML;
tdescribe = table.rows[this.i].cells[2].innerHTML;
wd = table.rows[this.i].cells[3].innerHTML;
dep = table.rows[this.i].cells[4].innerHTML;
// ... etc more code
The javascript works but any td can be clicked, I am after only:
The first td clicked
Then get parent row
Then all child td's
I have been over dozens of StackOverflow posts and other sites as well... Thanks
And how do I add the event.preventDefault() to regular JS in such a case.
You'd bind the handler to the first .cell.
rows[i].cells[0].onclick = function () {
And then in the handler, access the .parentNode of this to get the row.
And since you're not closing over any variables except those in the function itself (and outside that function, of course), I'd just use a single handler instead of recreating it in the loop.
function addRowHandlers() {
var table = document.getElementById("checktable2");
var rows = table.getElementsByTagName('tr');
var tid = '';
var tdate = '';
var tdescribe = '';
var wd = '';
var dep = '';
var tisclr = '';
for (var i = 1; i < rows.length; i++) {
rows[i].i = i;
rows[i].cells[0].onclick = handler;
}
function handler() {
var row = this.parentNode;
tid = this.innerText;
tdate = row.cells[1].innerHTML;
tdescribe = row.cells[2].innerHTML;
wd = row.cells[3].innerHTML;
dep = row.cells[4].innerHTML;
// etc more code
}
}
I'd probably use a loop to get the desired content too. Maybe like this:
function handler() {
var row = this.parentNode;
var props = ["tid", "tdate", "tdescribe", "wd", "dep"];
var content = props.reduce(function(obj, key, i) {
obj[key] = row.cells[i][i ? "innerHTML" : "innerText"];
return obj;
}, {});
// etc more code
}
Now instead of variables, you have properties of the content object.

Can't clear inputs in Javascript

I'm doing practical Javascript course on watchandcode.com and my code is exactly the same as the instructor's, but the part where it clears the inputs does not work here.
changeTodo: function () {
var changeTodoPositionInput = document.getElementById('changeTodoPositionInput').valueAsNumber;
var changeTodoTextInput = document.getElementById('changeTodoTextInput').value;
todoList.changeTodo(changeTodoPositionInput, changeTodoTextInput);
// THIS PART DOESN'T WORK
changeTodoPositionInput.value = '';
changeTodoTextInput.value = '';
}
The function does its job, it's just those last two lines that don't work.
You're trying to clear a value and not input elements, you have to get the DOM elements first :
var changeTodoPositionInput = document.getElementById('changeTodoPositionInput');
var changeTodoTextInput = document.getElementById('changeTodoTextInput');
Then get the value after that from them :
todoList.changeTodo(changeTodoPositionInput.valueAsNumber, changeTodoTextInput.value);
And now you could clear the value of the both inputs using :
changeTodoPositionInput.value = '';
changeTodoTextInput.value = '';
FULL CODE :
changeTodo: function() {
var changeTodoPositionInput = document.getElementById('changeTodoPositionInput');
var changeTodoTextInput = document.getElementById('changeTodoTextInput');
todoList.changeTodo(changeTodoPositionInput.valueAsNumber, changeTodoTextInput.value);
changeTodoPositionInput.value = '';
changeTodoTextInput.value = '';
}
Hope this helps.
You can try this:
var changeTodoPositionInput = document.getElementById('changeTodoPositionInput').value = "";
var changeTodoTextInput = document.getElementById('changeTodoTextInput').value = "";

How to pass parameters to a javascript function on onclick?

I have a script where i want to call another function on onclick by passing parameters.I want to call remove_product function .How can i achieve this?
function load_cart(){
$('.mini-cart-products').html('');
var url = $('.ajax-url').attr('href');
var t = 0;
// console.log(url);
$.ajax({
url : url,
dataType:'json',
success:function(result){
if(result.length > 0)
{
var image = $('.mini-cart-image a img');
var prod_name = $('.mini-cart-name a');
var attribute = $('.mini-cart-attributes');
var pricing = $('.mini-cart-pricing');
$.each(result, function(key, val){
var remove_url = val.remove;
var barcode = val.barcode;
var cart_id = val.cart_id;
console.log("remove_url :"+remove_url+" barcode : "+barcode+" cart_id : "+cart_id);
var productDiv = $( "<div class='mini-cart-product clearfix'></div>" );
var nameDiv = '<div class="mini-cart-name font">'+val.name+'</div>';
var attributes = $( "<div class='mini-cart-attributes'></div>" );
var colorAttr = '<div class="attribute"><span class="label">Colour: </span><span class="value">'+val.color+'</span></div>';
var sizeAttr = '<div class="attribute"><span class="label">Size&nbsp&nbsp&nbsp: </span><span class="value">'+val.size+'</span></div>';
var remove = '<div class="mini-cart-remove"><a onclick="remove_product(remove_url,barcode,cart_id)">Remove</a></div>';
The line of remove var should be something like that.
var remove = '<div class="mini-cart-remove"><a onclick="remove_product(\''+remove_url+'\',\''+barcode+'\',\''+cart_id+'\')">Remove</a></div>';
This will solve your problem
Sample fiddle
You can do with html onclick:
<button onclick="myFunction(param1, param2)">Click me</button>
or via jQuery
$(button).on('click', function() {
myFunction(param1, param2);
});
Here's the same thing as other answers but without jquery: https://jsfiddle.net/7L5ypo2r/
var testButton = document.getElementById('test-button')
testButton.onclick = function(){
//your code would go here
alert("test");
};
You should declare on the top of your javascript code a member variable.
<script>
var remove_product = null;
function yourFunction () {
remove_product = 'your_value';
}
$("#yourButton").on('click', function (event) {
alert(remove_product);
}
</script>

How to find the number of form elements that are getting passed to e.parameter in GAS?

In Google App Scripts (GAS), I want to be able to add and remove TextBox and TextArea elements to a FlexTable (that's being used as a form) and not worry about how many there are. I've named the text elements based on a counter to make this process easier.
So, is there a way to get the number of inputs (TextBox + TextArea) passed to e.parameter after the form is submitted?
Here's the relevant code from the FlexTable:
function doGet() {
var app = UiApp.createApplication();
var flex = app.createFlexTable().setId('myFlex');
var counter = 0;
var row_counter = 0;
...
var firstnameLabel = app.createLabel('Your FIRST Name');
var firstnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, firstnameLabel);
flex.setWidget(row_counter, 2, firstnameTextBox);
row_counter++;
counter++;
var lastnameLabel = app.createLabel('Your LAST Name');
var lastnameTextBox = app.createTextBox().setWidth(sm_width).setName('input' + counter).setText(data[counter]);
flex.setWidget(row_counter, 1, lastnameLabel);
flex.setWidget(row_counter, 2, lastnameTextBox);
row_counter++;
counter++;
...
var submitButton = app.createButton('Submit Proposal');
flex.setWidget(row_counter, 2, submitButton);
var handler = app.createServerClickHandler('saveProposal');
handler.addCallbackElement(flex);
submitButton.addClickHandler(handler);
var scroll = app.createScrollPanel().setSize('100%', '100%');
scroll.add(flex);
app.add(scroll);
return app;
}
And here's the code for the ClickHandler (notice that I currently have 39 elements in my FlexTable):
function saveProposal(e){
var app = UiApp.getActiveApplication();
var userData = [];
var counter = 39;
for(var i = 0; i < counter; i++) {
var input_name = 'input' + i;
userData[i] = e.parameter[input_name];
}
So, is there a way to get the number of elements (in this case 39) without manually counting them and assigning this value to a variable?
I'm new at this stuff and I'd appreciate your help.
Cheers!
The simplest way is to add a hidden widget in your doGet() function that will hold the counter value like this :
var hidden = app.createHidden('counterValue',counter);// don't forget to add this widget as a callBackElement to your handler variable (handler.addCallBackElement(hidden))
then in the handler function simply use
var counter = Number(e.parameter.counterValue);// because the returned value is actually a string, as almost any other widget...
If you want to see this value while debugging you can replace it momentarily with a textBox...
You can search for arguments array based object.
function foo(x) {
console.log(arguments.length); // This will print 7.
}
foo(1,2,3,4,5,6,7) // Sending 7 parameters to function.
You could use a while loop.
var i = 0;
var userData = [];
while (e.parameter['input' + i] != undefined) {
userData[i] = e.parameter['input' + i];
i++;
};
OR:
var i = 0;
var userData = [];
var input_name = 'input0';
while (e.parameter[input_name] != undefined) {
userData[i] = e.parameter[input_name];
i++;
input_name = 'input' + i;
};

A javascript function that complete another function sent as a parameter?

In the following javascript function window.setInterval(function,milliseconds) I can do the following:
var myvarible = function(){alert('Popup');};
window.setInterval(myvarible,5000);
now every 5 seconds my webpage will alert the message 'popup'
How can I make my own function do the parameter myvarible, as see above? This is what I am trying below, but it does not work.
text = "";
var myvarible = function() {
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
}
function howLong(the_function){
var starting_time = new Date().getMilliseconds();
the_function //do the function here
var finishing_time = new Date().getMilliseconds();
var difference = finishing_time-starting_time;
document.write(difference);
}
howLong(myVarible); //call my howLong function
I hope you understand me, I have tried to make myself as clear as possible and I am new to javascript so please try to keep the answers as simple as possible.
Thanks for your help
Put () after the variable to call it as a function:
the_function(); // do the function here
You have to make 3 corrections.
1.) calling howLong(myVarible); should be howLong(myvarible); because you are defining function as myvarible
2.)You have to call the function add () in function howLong
`the_function() //do the function here`
3.) define cars.
This worked for me
<script>
text = "";
var cars = [1,2,3];
var myVarible = function() {
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
}
function howLong(the_function){
var starting_time = new Date().getMilliseconds();
the_function() //do the function here
var finishing_time = new Date().getMilliseconds();
var difference = finishing_time-starting_time;
document.write(difference);
}
howLong(myVarible); //call my howLong function
</script>

Categories