I am trying to add and subtract values when the user clicks on the radio button. All the radio buttons are dynamically created from database values.
There maybe multiple categories inside one heading but user will be able to choose only one. I am stuck in subtracting the value when the user selects another option.
If you are kind enough ;), you can check this pasting in your editor (oh yeah.. I am a total newbie when it comes to programming.)
Any solution or different approach will be much much much appreciated.
Thanks...
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
.active {
background: #ccc;
}
.program {
border:1px solid blue;
}
.program td, .program th {
padding:10px;
border:1px solid grey;
}
.grandTotal {
width:200px;
height:35px;
font-size:18px;
font-weight:bold;
text-align:center;
line-height:35px;
background-color:#999;
margin-top:35px;
}
</style>
</head>
<body>
<div class="program-box">
<span>You can select or deselect the radio button</span>
<h2>Heading1</h2>
<table class="program" cellpadding="0" cellspacing="1">
<tr>
<th class="w-5"></th>
<th class="w-35">Name</th>
<th class="w-30">Location</th>
<th class="w-10">#days</th>
<th class="w-10">Price</th>
</tr>
<tr>
<td><input name=cat1 value=3 id=3 type='radio' class='v'/></td>
<td>categeory 1</td>
<td>location1</td>
<td>5</td>
<td class="price1">100</td>
</tr>
</table>
<h2>Heading2</h2>
<table class="program" cellpadding="0" cellspacing="1">
<tr>
<th class="w-5"></th>
<th class="w-35">Name</th>
<th class="w-30">Location</th>
<th class="w-10">#days</th>
<th class="w-10">Price</th>
</tr>
<tr>
<td><input name=cat2 value=1 id=1 type='radio' class='v'/></td>
<td>category2</td>
<td>location2</td>
<td>4</td>
<td class="price1">200</td>
</tr>
<tr>
<td><input name=cat2 value=2 id=2 type='radio' class='v'/></td>
<td>category2</td>
<td>location3</td>
<td>8</td>
<td class="price1">150</td>
</tr>
</table>
<div class="price">
<div class="grandTotal">1800</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input[type='radio']").mousedown(function(e) {
if ($(this).attr("checked") == true) {
setTimeout("$('input[id=" + $(this).attr('id') + "]').removeAttr('checked');", 200);
}
else {
return true
}
});
});
$(".v").click(function() {
$(this).toggleClass("active");
$(this).closest('.program').find('.v').not(this).removeClass('active');
var actPrice = 1800; // default 1800
actPrice = parseInt(actPrice); // convert this to integer
var isSet = $(this).hasClass("active");
var grandTotal=$(".grandTotal").text();
if (grandTotal=="")
{
//alert('no total till now');
var grandTotal=0;
} else {
grandTotal=parseInt(grandTotal);
//alert(grandTotal);
}
var div=parseInt($(this).closest('tr').find(".price1").text());
if(isSet)
{
if(grandTotal>0){
var total = grandTotal+div;
} else {
var total = actPrice+div;
}
//alert(total);
$(".grandTotal").html(total);
} else
{
var div2 = parseInt($(this).closest('tr').find(".price1").text());
var newTotal = grandTotal-div2;
$(".grandTotal").html(newTotal);
}
});
</script>
</div>
</body>
</html>
You were pretty close! I modified your code slightly and cleaned some things up, but you were almost there:
$(document).ready(function() {
$("input[type='radio']").mousedown(function(e) {
var self = this;
/* Use 'checked' property instead of wrapping in jQuery object */
if (self.checked) {
/* Use setTimeout with a function instead of JS string */
setTimeout(function() {
self.checked = false;
}, 200);
}
else {
return true;
}
});
/* Assign click handler inside document.ready: */
$(".v").click(function() {
/* Cache selectors that are used over and over: */
var $this = $(this);
var $grandTotalContainer = $(".grandTotal");
/* Call parseInt with radix parameter: */
var grandTotal = parseInt($grandTotalContainer.text(), 10);
var price =
parseInt($this.closest('tr').find(".price1").text(), 10);
var siblingAmounts = 0;
var name = $this.attr("name");
/* Find prices of items in the same "group": */
$("input[name='" + name + "'].active")
.not($this)
.each(function() {
siblingAmounts +=
parseInt($(this).closest("tr").find(".price1").text(), 10);
});
$this.toggleClass("active");
$("input[name='" + name + "']").not($this).removeClass("active");
if ($this.hasClass("active")) {
grandTotal -= siblingAmounts;
grandTotal += price;
}
else {
grandTotal -= price;
}
$grandTotalContainer.html(grandTotal);
});
});
Notes:
Calling setInterval with a JavaScript string instead of a function is considered bad practice because it calls eval() which can cause problems.
Directly accessing DOM element properties where it works is preferrable to wrapping this in a jQuery object and using jQuery methods to access those properties.
Calling parseInt with the radix parameter is highly recommended because otherwise JavaScript tries to assume the radix.
I removed the code that worked with a default grand total and just parsed out the value inside the grand total div.
I select siblings of the clicked input using the attribute equals selector
Make sure and cache jQuery results that you use over and over. There's overhead to executing jQuery functions that you can avoid if you cache the results of queries.
You shouldn't use integers as ids for HTML elements, as they're invalid under the HTML 4.01 specification.
Here's a working example: http://jsfiddle.net/andrewwhitaker/8Atf8/1/
Hope that helps!
Related
I have following code to highlight table record with three different colors when user click a checkbox. How can I use a cookie to save the clicked value with grab the cookie every time the user opens the page everytime? I haven't no idea how cookies are used. Answer would be really appreciate
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<style>
.highlight-red {
background-color: red;
}
.highlight-green {
background-color: green;
}
.highlight-yellow {
background-color: yellow;
}
</style>
<div class="col-lg-10">
<table id="Table" border="1">
<tr class="highlight">
<td><input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" /></td>
<td>Click me</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changeSoma(data, color){
if(data.checked && color == 'red'){
$(data).parent().parent().addClass("highlight-red");
}
else{
$(data).parent().parent().removeClass("highlight-red");
}
if(data.checked && color == 'green'){
$(data).parent().parent().addClass("highlight-green");
}
else{
$(data).parent().parent().removeClass("highlight-green");
}
if(data.checked && color == 'yellow'){
$(data).parent().parent().addClass("highlight-yellow");
}
else{
$(data).parent().parent().removeClass("highlight-yellow");
}
}
</script>
</body>
</html>
localStorage is easier than cookie I thought . You can set and get by localStorage.setItem or localStorage.getItem and it will remain until you remove them !!!
<script>
var cond = JSON.parse(localStorage.getItem("check"));
for(var i in cond) {
if(cond[i]) {
$("#"+i).attr("checked",true);
$("#"+i).parent().parent().addClass("highlight-"+cond[i]);
}
}
function changeSoma(data, color){
var state;
if(localStorage.getItem("check") == null) {
state = {cb1:0,cb2:0,cb3:0};
} else{
state = JSON.parse(localStorage.getItem("check"));
}
if(data.checked) {
$(data).parent().parent().addClass("highlight-"+color);
state[data.id]= color;
} else {
$(data).parent().parent().removeClass("highlight-"+color);
state[data.id]= 0;
}
localStorage.setItem("check",JSON.stringify(state));
}
</script>
it easier using localStorage but since you're using jQuery then use jQuery cookie plugin
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<style>
.highlight-red {
background-color: red;
}
.highlight-green {
background-color: green;
}
.highlight-yellow {
background-color: yellow;
}
</style>
<div class="col-lg-10">
<table id="Table" border="1">
<tr class="highlight">
<td><input type="checkbox" name="cb1" id="cb1" value="y" onChange="changeSoma(this, 'red')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" onChange="changeSoma(this, 'green')" /></td>
<td>Click me</td>
</tr>
<tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" onChange="changeSoma(this, 'yellow')" /></td>
<td>Click me</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
$(document).ready(function() {
var checkedBox = $.cookie('checkedBox');
console.log(checkedBox);
if(checkedBox !== undefined) {
// to check only
//$(checkedBox).attr('checked', true);
// emulate click to check and change the class
$(checkedBox).each(function() {
this.click();
})
}
})
function changeSoma(data, color) {
if(data.checked && color == 'red') {
$(data).parent().parent().addClass("highlight-red");
}
else {
$(data).parent().parent().removeClass("highlight-red");
}
if(data.checked && color == 'green') {
$(data).parent().parent().addClass("highlight-green");
}
else {
$(data).parent().parent().removeClass("highlight-green");
}
if(data.checked && color == 'yellow') {
$(data).parent().parent().addClass("highlight-yellow");
}
else {
$(data).parent().parent().removeClass("highlight-yellow");
}
// set cookie
var checked = "";
$('input[type="checkbox"]').each(function() {
if($(this).prop('checked')) {
checked += "#" + this.id + ","; // #cb, jQuery id selector
}
})
checked = checked.replace(/,$/, '')
console.log(checked);
$.cookie('checkedBox', checked);
}
</script>
</body>
</html>
I'm assuming you want the values to be selected still even when the user goes to a different page on your site and then select them again once back in that page.
As stated here, you set the cookies using the document.cookie javascript property.
The property mentioned above, however, is a semicolon separated key-value pair. you'll have to manipulate the string in order to add/edit a value.
Once you've added the value that you want, you can once again read it and then set the rows you want to be selected.
To get the selected value, you could use $(data).val() and put it inside changeSoma(). From there, you could check if it's checked $(data).is(':checked'). If it's checked, add it to document.cookie like document.cookie = "key=value; key2=value2;"
Currently I'm working on a dynamic table where user can add and remove rows form the table to input data...how do I change my user's input 'name/id/class' on adding rows. Any help will be appreciated. Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic table</title>
<script src="https://code.jquery.com/jquery-1.8.3.min.js" integrity="sha256-YcbK69I5IXQftf/mYD8WY0/KmEDCv1asggHpJk1trM8="
crossorigin="anonymous"></script>
<script>
$(document).ready( function() {
$('#butVal').click(function(){
var rowLen = $('tr.tabRow').length;
if(rowLen>9)
{
alert("no of row is reached 10");
}
else
{
$("tr.tabRow:first").clone(true).appendTo("#table-2>tbody");
$(".tabRow:last").children("td").children("input").each(function(index, element){
$(element).val("");
});
}
});
$(document).on("click", "button.remove", function(){
if($(this).parents("tr").siblings("tr.tabRow").length > 0)
{
$(this).closest("tr.tabRow").remove();
}
else
{
alert("you can.t remove this record");
}
});
$(document).on("click", ".add, .remove", function(){
$("td.sno").each(function(index,element){
$(element).text(index + 1);
});
});
});
</script>
</head>
<body>
<div class="total">
<table id="table-2" class="add" border ="1">
<thead>
<tr>
<th class="small">S.No</th>
<th class="sizing"> Description</th><th>Quantity</th>
<th> Price </th>
<th><button id="butVal"> + </button></th>
</tr>
</thead>
<tbody>
<tr class="tabRow" id="1item">
<td class="sno">1</td>
<td> <input class="desc" type="text" name="desc"/> </td>
<td> <input class="qty" type="text" name="qty"/> </td>
<td> <input class="price" type="text" name="price"/> </td>
<td><button class="remove">Remove</button></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
So you have tried using ".addClass() Jquery function" or removeclass() function??
Heres an example of .addClass():
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>addClass demo</title>
<style>
p {
margin: 8px;
font-size: 16px;
}
.selected {
color: blue;
}
.highlight {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
<script>
$( "p" ).last().addClass( "selected" );
</script>
</body>
</html>
So, whenever a new entry is created, you need to change the class attribute of the input elements:
$('#butVal').click(function () {
var rowLen = $('tr.tabRow').length;
if (rowLen > 9) {
alert("no of row is reached 10");
} else {
$("tr.tabRow:first").clone(true).appendTo("#table-2>tbody");
$(".tabRow:last").children("td").children("input").each(function (index, element) {
var className = $(element).attr("class"); // get the current class attribute of the element
$(element).attr("class", className + rowLen); // append the current row number to the class
$(element).val("");
});
}
});
Note: when you remove rows, the classes will not change. It could happen that you have the classes desc, then desc1, but then desc3.
I've been trying many different methods and rewriting my code to achieve something that I feel is quite simple but I can't seem to get it.
I have two increment/decrement buttons but I want to disable the click function on the subtract button when the value reaches 0 as to not input negative numbers.
Currently on my jsfiddle I have the calculator working, however when I try to disable the subtract button when the value is 0, it disables the button completely, even when the value is no longer 0. It seems jQuery is not checking to see if the value has changed.
Any ideas on how can I fix this? Thanks!
Example here:
https://jsfiddle.net/jony000/frupofqe/22/
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
JQuery
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function() {
showers++;
rate.html(showers);
})
minus.click(function() {
showers--;
rate.html(showers);
})
/*if (showers == 0) {
minus.css("pointer-events","none");
} else{
minus.css("pointer-events", "auto");
}*/
You have to check if shower is zero inside the click event listener for the minus element:
minus.click(function() {
rate.html(--showers);
if (showers === 0) {
minus.css("pointer-events", "none");
} else{
minus.css("pointer-events", "auto");
}
});
Check for 0 before you decrement. I believe its more clearly readable to just not decrement it rather than disabling the control, unless you had other logic thats not shown in the demo.
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
plus.click(function(){
showers++;
rate.html(showers);
})
minus.click(function(){
if (showers <= 0)
return;
showers--;
rate.html(showers);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p align="center">
How often do you shower?
</p>
<table class="shower">
<tbody>
<tr>
<td class="rate-minus">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a Day
</p>
you just need to move your entire if block at the bottom inside of your functions... or better yet, create a new function and call that one inside the others. Here's an example
var showers = 0;
var plus = $(".rate-plus");
var minus = $(".rate-minus");
var rate = $(".shower-rate");
//This is new
var checkForZero = function() {
if (showers == 0) {
minus.css("pointer-events","none");
} else {
minus.css("pointer-events", "auto");
}
};
plus.click(function(){
showers++;
rate.html(showers);
checkForZero(); //call new function
})
minus.click(function(){
showers--;
rate.html(showers);
checkForZero(); //call new function
})
you can do something like this.
var rateMinus = $(".rate-minus");
var value = 0;
updateRateMinus(); // update on initial load
$(".rate-plus").click(function() {
parseInt($(".shower-rate").text(value + 1));
value = value + 1;
updateRateMinus();
});
$(".rate-minus").click(function() {
parseInt($(".shower-rate").text(value - 1));
value = value - 1;
updateRateMinus();
});
function updateRateMinus() {
if ($(".shower-rate").text() == 0) {
rateMinus.css('pointer-events', 'none');
} else {
rateMinus.css("pointer-events", "auto");
}
}
You could just set up an call that would check a given condition (if your value is 0) and use that to toggle if your subtract button was enabled or disabled via a ternary operation :
minus.css("pointer-events",showers === 0 ? "none" : "auto");
Then you could simply check for that scenario when either of your events occur :
plus.click(function(){
showers++;
UpdateRate();
})
minus.click(function(){
showers--;
UpdateRate();
})
function UpdateRate() {
// This will disable your button if showers is 0
minus.css("pointer-events",showers === 0 ? "none" : "auto");
rate.html(showers);
}
Example
var rateMinus = $(".rate-minus");
var ratePlus = $(".rate-plus");
var rate = $(".shower-rate");
var value = 0;
ratePlus.click(function() {
value++;
UpdateRate();
})
rateMinus.click(function() {
value--;
UpdateRate();
})
function UpdateRate() {
debugger;
// This will disable your button if showers is 0
rateMinus.css("pointer-events", value === 0 ? "none" : "auto");
rate.html(value);
}
table {
margin: auto;
color: #cecece;
}
.shower td {
padding: 10px;
}
.rate-minus,
.rate-plus,
.period-minus,
.period-plus {
width: 50px;
height: 50px;
background: #a8d6ff;
border-radius: 100%;
text-align: center;
font-size: 24px;
color: black;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How often do you shower?
<table class="shower">
<tbody>
<tr>
<td class="rate-minus" id="test">
-
</td>
<td class="shower-rate">0</td>
<td class="rate-plus">
+
</td>
</tr>
</tbody>
</table>
<p align="center">
Times a
</p>
<table class="shower">
<tbody>
<tr>
<td class="period-minus">
-
</td>
<td class="shower-period">
Day
</td>
<td class="period-plus">
+
</td>
</tr>
</tbody>
</table>
I'm just starting Angular JS and trying to have a scrollbar appearing as I add an element in the list which would be populated in the box of the contents.
I installed ng-scrollbar from here. https://github.com/asafdav/ng-scrollbar
HTML:
<link rel="stylesheet" href="../dist/ng-scrollbar.min.css" >
<style>
.scrollme {
max-height: 100px;
}
</style>
</head>
<body>
<div ng-app="DemoApp">
<div class="container" ng-controller="DemoController">
<table border="0" width="100%">
<div class="scrollme" ng-scrollbar rebuild-on="rebuild:me" is-bar-shown="barShown">
<tr>
<th width="2%"></th>
<th width="14%">Name</th>
<th width="85%">Address</th>
</tr>
<tr>
<td>
<img src="addImageButton.png" ng-click="addRow()" />
</td>
<td class="inlineBlock">
<input type="text" ng-model="row.name" />
</td>
<td>
<input ng-model="row.addr" />
</td>
</tr>
<tr ng-repeat="row in rowList">
<td>
<img src="removeImageButton.png"ng-click="removeRow($index)" />
</td>
<td>{{row.name}}</td>
<td>{{row.client}}</td>
</tr>
</div>
</table>
</div>
</div>
</body>
JavaScript:
(function () {
'use strict';
var app = angular.module('DemoApp', ['ngScrollbar']);
app.controller('DemoController', DemoController);
function DemoController($scope) {
// portfolio and broker tabs
$scope.row = {}
$scope.row.name = "";
$scope.row.addr = "";
$scope.rowList = [];
// adding a row to list
$scope.addRow = function() {
var data = {};
data.name = $scope.row.name;
data.addr = $scope.row.addr;
$scope.rowList.push(data);
$scope.row.name = "";
$scope.row.addr = "";
console.log($scope.rowList);
}
// removing a row from the list
$scope.removeRow = function(obj) {
console.log('end' + $scope.rowList);
if(obj != -1) {
$scope.rowList.splice(obj, 1);
}
}
$scope.$on('scrollbar.show', function(){
console.log('Scrollbar show');
});
$scope.$on('scrollbar.hide', function(){
console.log('Scrollbar hide');
});
// $scope.$on('loopLoded', function(evt, index) {
// if(index == $scope.me.length-1) {
// $scope.$broadcast('rebuild:me');
// }
// });
}
})();
It's part of my code so it might not fully make sense. But the way it works is that if I pressed the addImageButton, it would add a row which will add a row on the web. And conversely, removeImageButton will delete a row which will show on the web immediately. I need a scroll bar appearing once it reaches the height 100px. I checked the last answer of the ng-scrollbar is not working with ng-repeat
as well but it didn't work. Would be great if I could get some help with the detailed explanation. :) Thanks!
Figured out! I need to put the broadcast method in addRow and removeRow methods. Also, I had to put the out from the
I am still new to javascript and HTML. My task is to generate 2 random integer values from 1 to 3. Upon pressing the "Match!" button, an alert box informs the user if the two numbers are the same or not the same. Not sure why my code isn't working. Any help is appreciated.
Demo: https://jsfiddle.net/1rp5xvte/5/#&togetherjs=pJcEH56yoK
$(document).ready(function(){
function myFunction()
{
document.getElementById("generatedNum").innerHTML = Math.random();
{
if (generateNum1 == generateNum2) {
alert ("Both numbers are the same");
}
else {
alert("Both numbers are different");
}
displayGeneratedNum ();
}
}
});
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lab Report</title>
<script src="jquery.js"></script>
<script src="myScript.js"></script>
<style>
body{font-size:40px;
text-align:center;
background-color: antiquewhite;}
table {margin-top:100px;
background-color:white;}
td { width:150px;}
span {font-size:40px;}
#correctScore{
background-color:green;
}
#wrongScore{
background-color:red;
}
#missedScore{
background-color:blueviolet;
}
.numberStyle {
padding: 10px 10px 10px 10px;
color:blue;
}
.numberStyle span {
font-size:100px;
}
</style>
</head>
<body>
<table width="800" border="1" align="center">
<tr>
<td id="generatedNum" colspan="6" align="left"><span>Random Numbers
generated : 1</span></td>
</tr>
<tr>
<td colspan="3" align="center">Number 1</td>
<td colspan="3" align="center">Number 2</td>
</tr>
<tr>
<td colspan="3" id="number1" class="numberStyle"><span>1</span></td>
<td colspan="3" id="number2" class="numberStyle"><span>2</span></td>
</tr>
<tr height="50px";>
<td colspan="6"><input type="button" value="MATCH!" style="font-size:50px;">
</input></td>
</tr>
<tr>
<td>Correct:</td>
<td id="correctScore"><span>0<span></td>
<td><span>Wrong<span></td>
<td id="wrongScore"><span>0<span></td>
<td><span>Missed<span></td>
<td id="missedScore"><span>0<span></td>
</tr>
</table>
</body>
</html>
try this code
<html><body><label id='lbl'></label><button id="btn">Match!</button><script src="https://code.jquery.com/jquery-2.2.1.min.js"></script><script>
function randomNumber(a,b)
{
if(b == undefined) {
b = a - 1;
a = 0;
}
var delta = b - a + 1;
return Math.floor(Math.random()*delta) + a
}
$(document).ready(function(){
$('#btn').click(function()
{
var generateNum1 = randomNumber(1,3);
var generateNum2 = randomNumber(1,3);
if (generateNum1 == generateNum2) {
alert ("Both numbers are the same");
}
else {
alert("Both numbers are different");
}
$('#lbl').html(generateNum1 + ";" + generateNum2);
})
});
</script></body></html>
You need a function that generated a random integer within a range.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
button.addEventListener('click', function() {
var num1 = getRandomInt(1, 3);
var num2 = getRandomInt(1, 3);
alert(num1 === num2 ? 'Both numbers are the same' : 'Both numbers are different');
});
JSFiddle Demo: https://jsfiddle.net/1rp5xvte/1/