Clicking a button with same value in socket.io - javascript

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>

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>

Error message not working in simple javascript form validation

Here is the following code which is not working to show error message when submitted.
The problem is that the error message is not displayed properly when clicked once but if you give multiple clicks it works.
Help will be appreciated.
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>JavaScript form validation - checking all letters</title>
<style type="text/css">
li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}
</style>
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Enter your Name and Submit</h2>
<form name="form1" action="#">
<ul>
<li>
Code:
</li>
<li id="myList">
<input type='text' name='text1'/>
<p id="error"></p>
</li>
<li class="rq">
*Enter alphabets only.
</li>
<li> </li>
<li>
<input type="submit" name="submit" value="Submit" onclick="allLetter(document.form1.text1)" />
</li>
<li> </li>
</ul>
</form>
</div>
<script type="text/javascript">
function allLetter(inputtxt) {
var letters = /^[A-Za-z]+$/;
if(inputtxt.value.match(letters)) {
document.getElementById("error").innerHTML="error here";
return false;
} else {
document.getElementById("error").innerHTML="success";
return true;
}
}
</script>
</body>
</html>
Your problem and solution is quite simple.
When you click the form button, the form automatically submits itself and that's why you see nothing.
Add this to your button code so you can prevent the default functionality of the submit input:
<input type="submit" name="submit" value="Submit" onclick="allLetter(document.form1.text1);return false" />
That should solve it:
You should to use event.preventDefault method to prevent the page refresh.
So, your function should look like this:
function allLetter(event) {
event.preventDefault();
var letters = /^[A-Za-z]+$/;
if (document.form1.text1.value.match(letters)) {
document.getElementById("error").innerHTML="error here";
//return false;
} else {
document.getElementById("error").innerHTML="success";
return true;
}
}
It should be called in the following way:
<input type="submit" name="submit" value="Submit" onclick="allLetter(event)" />

Use button value as button ID in 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.

Struggling to pull YouTube videos using api

Having some trouble with the YouTube API and hoping someone can help.
Here's my code:
HTML
<!doctype html>
<html lang="en">
<head>
<title>Video App</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Viral Videos App" />
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>
<h1 class="w100 text-center">Video </h1>
</header>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="#">
<p><input type="text" id="Search" placeholder="Type here..." autocomplete="off" class="form-control" /></p>
<p><input type="submit" value="Search" class="form-control btn btn-primary w100"></p>
</form>
<div id="results"></div>
</div>
</div>
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/app.js"></script>
<script src="https://apis.google.com/js/client.js?onload=init"> </script>
</body>
</html>
And here is my CSS
body { background: #1B2836; }
header { margin-top:30px; }
header a { color: #01FFBE; text-decoration: none; }
header a:hover { text-decoration: none; }
form { margin-top: 20px; }
form, #results {padding: 0 20px; }
.item { margin-bottom: 25px; }
.w100 { width: 100%; }
.btn-primary { background: #01FFBE; border-color: #00C693; }
.btn-primary:hover, .btn-primary:active, .btn-primary:focus { background: #00C693; border color: #00C693; }
And here is my Javascript
$(function() {
$("form").on("submit", function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
publishedAfter: "2015-01-01T00:00:00Z"
});
// execute the request
request.execute(function(response) {
var results = response.result;
$.each(results.items, function(index, item) {
console.log(item);
});
});
});
});
function init() {
gapi.client.setApiKey("AIzaSyDnp3yk0p6yWqpcK2iggS1WkwXMyEFYVvI");
gapi.client.load("youtube", "v3", function() {
//yt api is ready
});
}
It appears fine in my live preview and I can type and search but then I hit an error if I open the console.

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