Use button value as button ID in javascript - javascript

Here is the image of the situation i'm facing
screenshot IMAGE I have 2 buttons which get their values from a html form, i am using node js and sockets for this. when i click a button in one tab button in other tab with same id is getting clicked, but what i want is when i click a button with value 1(example) the button with value 1 should get clicked which is not happening here. i was thinking for a way where i can use button value as button id can anyone help me.
EDIT
I was thinking to use IF/ELSE condition where when we click a button it will search for a button with the value of the clicked button and trigger it
app.js
const io = require('socket.io')(3000);
io.on('connection', function (socket) {
console.log('a client has connected');
socket.on('clicked', function() {
io.emit('clicked');
});
socket.on('clicked1', function() {
io.emit('clicked1');
});
});
console.log('socket.io server started at port 3000');
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script>
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Oxygen:400,300,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body bgcolor="#3C4C55">
<script>
if (document.all||document.getElementById){
document.write('<style>.tictac{')
document.write('width:50px;height:30px;padding: 5px; font-weight: bold; cursor: pointer; border-radius: 5px; border: 1px solid #D9D9D9; font-size: 75%;')
document.write('}</style>')
}
</script>
<div class="main">
<center>
</br></br></br></br></br></br>
<form method="get" action="button.html">
<table id="employeeTable" border="15" cellpadding="5" align="center" style="background-color:orange" >
<tr>
<td>
<input type="number" id="sq1" name="sqrone" placeholder="Value" class="tictac" />
</td>
<td>
<input type="number" id="sq2" name="sqrtwo" placeholder="Value" class="tictac" />
</td>
</tr>
</table>
</br></br>
<div class="submit">
<input type="submit" value="Submit" onclick="saveVal()">
</div>
<script type="text/javascript">
function saveVal() {
var squ1 = document.getElementById("sq1").value;
localStorage.setItem("sq1", squ1);
squ1 = localStorage.getItem("sq1");
var squ2 = document.getElementById("sq2").value;
localStorage.setItem("sq2", squ2);
squ2 = localStorage.getItem("sq2");
}
</script>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "dskstkcm"
}], "*")
}
</script>
</form>
</center>
</div>
</body>
</html>
button.html
<!doctype html>
<html>
<head>
<title>Testing socket.io</title>
<style>.tictac{
width:100px;height:100px;
padding: 10px;
font-weight: bold;
background:#16ed07;
color: #000000;
cursor: pointer;
border-radius: 10px;
border: 1px solid #D9D9D9;
font-size: 150%;
}
</style>
</head>
<body>
<form>
<input type="button" id="sq1" NAME="sqr1" class="tictac" value="Send!" onClick="onClickHandler(this)"/>
<input type="button" id="sq2" NAME="sqr2" class="tictac" value="Get!" onClick="onClickHandler(this)"/>
</form>
<script type="text/javascript">
var square1 = document.getElementById("sq1");
square1.value = localStorage.getItem("sq1");
var square2 = document.getElementById("sq2");
square2.value = localStorage.getItem("sq2");
</script>
<h2 id="alert"> waiting...</h2>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script>
var socket = io("http://localhost:3000");
socket.on('connect', function() {
document.getElementById("sq1").addEventListener("click", function () {
socket.emit("clicked");
});
document.getElementById("sq2").addEventListener("click", function () {
socket.emit("clicked1");
});
});
socket.on('clicked', function() {
var button = document.getElementById('sq1');
console.log('clicked');
document.getElementById("alert").innerHTML = "1 clicked";
onClickHandler(sq1);
});
socket.on('clicked1', function() {
var button = document.getElementById('sq2');
console.log('clicked1');
document.getElementById("alert").innerHTML = "2 clicked";
onClickHandler(sq2);
});
</script>
<script type="text/javascript">
function onClickHandler(elem) {
elem.style.background = 'red';
elem.style.color = 'black';
}
</script>
</body>
</html>

What you probably want to do is extract information on what button was clicked and then emit that data with socket.io. The second parameter of socket.emit can be an object that will be passed to listeners of socket.on('event', function(data){ /* data passed from socket.emit */ }). You will probably need to re-emit this data from the server in the same way.
Client example: https://jsfiddle.net/wcmtk5mj/
Make sure you remove the onClicked simulation when utilizing socket.emit and socket.on in the example above.

Related

Show Captured WebCam file name to Next Page in Python (Flask)

I am trying to capture an image from WebCam and show its file name on the next page when the user clicks the Upload button.
Currently, the snap function is taking the image and working fine. But When the users click on the Upload button, nothing happened.
Expected Output: Click on the Upload button will open a New Page (Test2) and show the file name.
My Code
app.py
#app.route('/Test', methods=['GET','POST'])
def Test():
if request.method == 'POST':
return render_template('Test2.html',data=request.form['file'])
return render_template('Test.html')
if __name__ == '__main__':
app.run(debug=True)
Test.html
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.26/webcam.min.js" integrity="sha512-dQIiHSl2hr3NWKKLycPndtpbh5iaHLo6MwrXm7F0FM5e+kL2U16oE9uIwPHUl6fQBeCthiEuV/rzP3MiAB8Vfw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<form method="POST" enctype="multipart/form-data" id="myForm">
<table>
<tr>
<td>Name/EmailId</td>
<td>: <input type="text" name="userID"></td>
</tr>
<tr>
<td><input type="button" value="Upload" onclick="upload()"></td>
</tr>
</table>
</form>
<div id="my_camera"></div>
<input type="button" onclick="snap()" value="Snap">
<div id="results"></div>
</body>
<script>
function ShowCam() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach('#my_camera');
}
window.onload= ShowCam;
function snap() {
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<img id="image" src="'+data_uri+'"/>';
} );
}
function upload() {
console.log("Uploading...")
var image = document.getElementById('image').src;
var form = document.getElementById('myForm');
var formData = new FormData(form);
formData.append("file", image);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Test");
// check when state changes,
xmlhttp.onreadystatechange = function() {
}
xmlhttp.send(formData);
console.log(formData);
console.log(formData.get('file'));
console.log(formData.get('userID'));
}
</script>
Test2.html
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<p> {{data}}
</body>
</html>

How to correctly execute a function JS with onclick?

I'm trying to execute a function by clicking on a span, but it tells me that it is undefined.
$(document).ready(function() {
function callTo(param) {
alert(param);
}
});
.file-up {
background: #f5f5f5 none repeat scroll 0 0;
border: 1px solid #ccc;
color: #383f45;
font-size: 12px;
margin-bottom: 10px;
padding: 6px;
font-size: 10px;
text-align: center;
text-transform: uppercase;
cursor: pointer;
}
<div>
<span class="file-up" onclick="callTo('test')">Click to call</span>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>
sample
</title>
</head>
<body>
<script>
function callTo(param) {
alert(param);
}
</script>
<div>
<span class="file-up" id="index" onclick="callTo('test')">
Click to call
</span>
</div>
</body>
This is a working example without using jQuery, just by vanilla javascript. Insert it and use it directly.
If you want me to post an answer which uses only jQuery for the stated task that you want to accomplish then please let me know.
This is code using jQuery, as you asked -
<!DOCTYPE html>
<html>
<head>
<title>
sample
</title>
</head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#index').click (function callTo() {
alert("Your values is :"+ $(this).data("value"));
});
});
</script>
<div>
<span class="file-up" id="index" data-value="test">
Click to call
</span>
</div>
Try to move your function definition away from $(documents).ready
<script>
function callTo(param) {
alert(param);
}
</script>
Or define event listener like
<script>
$(document).ready(function() {
$('.file-up').click(function() {
//action
});
});
</script>
(I'd better give it an id in this case and change the selector to #id instead of .file-up because other elements can have the same class applied)

calling a html function inside script in external js file

I have written a javascript function inside script tag of html file...
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll"></div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
<script type="text/javascript">
// set the focus to the input box
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}
function verify(arguments){
}
</script>
</body>
</html>
i need to move the function verify(arguments) to an external js file.i have to move that because i am calling a nodejs child process which requires a module to be included.
How can i move the function to a external js file and subsequently call verify function from html file.
Make three files as such. It will solve your issue.
index.html
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
<!-- insert these two lines -->
<script type="text/javascript" src="verify.js" ></script>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll">
</div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
</body>
</html>
verify.js
function verify() {
}
other.js
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}
You can just copy paste the function to a .js file (ex:verifys.js) and include the .js file in the HTML using

Clicking a button with same value in socket.io

I am stuck with this problem for so many day and i havent found any solution can any one help me solve this please. I have two buttons in my client page as shown HERE which listen to a server on port 3000. The button gets their values from a html form, so different clients have different values. At present i am able to click the buttons based on their ID that is if one client clicks a button with id sq1 the button with same id gets clicked automatically.
But what i want is when i click the button with value 1 the button with same value show be clicked automatically
app.js
const io = require('socket.io')(3000);
io.on('connection', function (socket) {
console.log('a client has connected');
socket.on('clicked', function() {
io.emit('clicked');
});
socket.on('clicked1', function() {
io.emit('clicked1');
});
});
console.log('socket.io server started at port 3000');
button.html
<!doctype html>
<html>
<head>
<title>Testing socket.io</title>
<style>.tictac{
width:100px;height:100px;
padding: 10px;
font-weight: bold;
background:#16ed07;
color: #000000;
cursor: pointer;
border-radius: 10px;
border: 1px solid #D9D9D9;
font-size: 150%;
}
</style>
</head>
<body>
<form>
<input type="button" id="sq1" NAME="sqrone" class="tictac" onClick="onClickHandler(this)"/>
<input type="button" id="sq2" NAME="sqrtwo" class="tictac" onClick="onClickHandler(this)"/>
</form>
<h2 id="alert"> waiting...</h2>
<script type="text/javascript">
var square1 = document.getElementById("sq1");
square1.value = localStorage.getItem("sq1");
var square2 = document.getElementById("sq2");
square2.value = localStorage.getItem("sq2");
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script>
var socket = io("http://localhost:3000");
socket.on('connect', function() {
document.getElementById("sq1").addEventListener("click", function () {
socket.emit("clicked");
});
document.getElementById("sq2").addEventListener("click", function () {
socket.emit("clicked1");
});
});
socket.on('clicked', function() {
//if condition
console.log('clicked');
document.getElementById("alert").innerHTML = "1 clicked";
onClickHandler(sq1);
});
socket.on('clicked1', function() {
//if condition
console.log('clicked1');
document.getElementById("alert").innerHTML = "2 clicked";
onClickHandler(sq2);
});
</script>
<script type="text/javascript">
function onClickHandler(elem) {
elem.style.background = 'red';
elem.style.color = 'black';
}
</script>
</body>
</html>
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Oxygen:400,300,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body bgcolor="#3C4C55">
<style>.tictac{
width:50px;height:30px;padding: 5px; font-weight: bold; cursor: pointer; border-radius: 5px; border: 1px solid #D9D9D9; font-size: 75%;
</style>
<center>
</br></br></br></br></br></br>
<form method="get" action="button.html">
<table border="15" cellpadding="5" align="center" style="background-color:orange" >
<tr>
<td>
<input type="number" id="sq1" name="sqrone" placeholder="Value" class="tictac" />
<input type="number" id="sq2" name="sqrtwo" placeholder="Value" class="tictac" />
</td>
</tr>
</table>
</br></br>
<div>
<input type="submit" value="Submit" onclick="saveVal()">
</div>
<script type="text/javascript">
function saveVal() {
var squ1 = document.getElementById("sq1").value;
localStorage.setItem("sq1", squ1);
squ1 = localStorage.getItem("sq1");
var squ2 = document.getElementById("sq2").value;
localStorage.setItem("sq2", squ2);
squ2 = localStorage.getItem("sq2");
}
</script>
</form>
</center>
</div>
</body>
</html>

How to make my form post to its self

I have a form in which users can submit issues, what I want to happen is when users hit the add button, i want what they add to be posted in the box below. So say the add something, x out the window and come back to add something else later what they added previously will still be there.
here is my fiddle
http://jsfiddle.net/grahamwalsh/rCB9V/
IssueList(html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Issue List</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Issuelist.js"></script>
<link type="text/css" rel="stylesheet" href="Issuelistcss.css" />
</head>
<body>
<div class='issuelist'>
<form data-bind="submit:addIssue">
Add Issue: <input type="text" data-bind='value:issueToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: issueToAdd().length > 0">Add</button>
</form>
<p>Your Issues:</p>
<select multiple="multiple" data-bind="options:allIssues, selectedOptions:selectedIssues"> </select>
<div>
<button data-bind="click: removeSelected, enable: selectedIssues().length > 0">Remove</button>
<button data-bind="click: sortIssues, enable: allIssues().length > 1">Sort</button>
</div>
</div>
</body>
</html>
IssueList (js)
$(document).ready(function(){
var Issuelist = function () {
this.issueToAdd = ko.observable("");
this.allIssues = ko.observableArray(["test"]);
this.selectedIssues = ko.observableArray(["test"]);
this.addIssue = function () {
if ((this.issueToAdd() != "") && (this.allIssues.indexOf(this.issueToAdd()) < 0))
this.allIssues.push(this.issueToAdd());
this.issueToAdd("");
};
this.removeSelected = function () {
this.allIssues.removeAll(this.selectedIssues());
this.selectedIssues([]);
};
this.sortIssues = function () {
this.allIssues.sort();
};
};
ko.applyBindings(new Issuelist());
});
IssueListcss
body { font-family: arial; font-size: 14px; }
.issuelist { padding: 1em; background-color: #87CEEB; border: 1px solid #CCC; max-width: 655px; }
.issuelist input { font-family: Arial; }
.issuelist b { font-weight: bold; }
.issuelist p { margin-top: 0.9em; margin-bottom: 0.9em; }
.issuelist select[multiple] { width: 100%; height: 8em; }
.issuelist h2 { margin-top: 0.4em; }
You could have the form 'post' to its self then make an ajax request for their new issue and put it inside a div. I would also hold off on so much on the javascript or have support for those without it:
getissues.php
getissues.php
<?php
/*
connect to your database code
*/
$query = "select * from issues";
$result = mysql_query($query, $connect);
while($row = mysql_fetch_array($result))
{
echo $row['issues'];
echo '<hr>';
}
?>
process.php
process.php:
<?php
/*
connect to your database
*/
$issue = strip_tags$_POST['issue'];
$query = "insert into issues (issue) values ('$issue')";
$result = mysql_query($query, $connect);
?>
main form page:
<!DOCTYPE HTML>
<html>
<head>
<title>issue page</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Issuelist.js"></script>
<link type="text/css" rel="stylesheet" href="Issuelistcss.css" />
<script type="text/javascript">
function check()
{
var request = $.ajax({
url: "getissues.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$("#issues").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function validate()
{
var issue = $("#issue");
var errcount = 0;
if (issue == "")
{
errcount++;
alert("enter something");
}
if (errcount == 0)
{
/*
make request to php script to put issue into database
*/
$.post("process.php",
{
issue:issue
},
function(data,status){
window.alert("Request done!");
check();
});
}
}
</script>
</head>
<body>
<form action="issuelist.html" method="post">
Add Issue: <input type="text" name="issue"/>
Add Issue: <input type="text" name="issue" id="issue"/>
<button onclick="validate()">submit</button>
</form>
<div id="issues" class="issues">
<!--your ajax fetched issues will appear here-->
</div>
</body>
</html>
hope this helps!

Categories