Javascript is not getting implemented while running python program - javascript

Python Code
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def button():
return render_template("buttons.html")
if __name__ == "__main__":
app.run(debug=True)
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Creating new channel</title>
<script src="{{url_for('static', filename = 'js/button.js')}}"></script>
</head>
<body>
<ul class="unordered"></ul>
<form>
<input type="text" class="name" placeholder="Create Channel" autocomplete="off" />
<button class="submit">Create Channel</button>
</form>
</body>
</html>
Javascript code
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('.submit').disabled = true;
document.querySelector('.name').onkeyup = () => {
// checking whether the input bar is empty or not
if (document.querySelector('.name').value.length > 0)
document.querySelector('.submit').disabled = false;
else
document.querySelector('.submit').disabled = true;
};
document.querySelector('.form').onsubmit = () => {
//Crearting a list item
const li = document.createElement('li');
li.innerHTML = document.querySelector('.name').value;
//Appending it to the unordered list
document.querySelector('.unordered').append(li);
//Clear input feild
document.querySelector('.name').value = '';
document.querySelector('.submit').disabled = true;
//Stop form from submitting
return false;
};
});
When i run this code seperately, meaning when i only run the HTML file in the webpage than the program runs perfectly (when you press the button then whatever is in the input feild, shows up as an unordered list). But when i am using the html file in a python file, it doesn't work(when i press the button the page refreshes and nothing happens)

Related

Prevent default on enter key with a button in Javascript

I have my HTML code:
<!DOCTYPE html>
<head>
<script src="../req.js"></script>
</head>
<link rel="stylesheet" href="style.css">
<html>
<body>
<h1> Recipes founder</h1>
<form class="example">
<input id ="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button id="searchRecipe" type="button" onkeydown="handler(e)" onclick="searchFile()"><i></i>Search</button>
</form>
<div id="content"></div>
</body>
</html>
and my js code associated with it:
function searchFile(e) {
// enter must do the same
const q = document.getElementById('query').value;
const total_q = `Title%3A${q}%20OR%20Description%3A${q}%20OR%20web%3A${q}`
fetch(
`http://localhost:8983/solr/recipe/select?indent=true&q.op=OR&q=${total_q}&rows=300`, { mode: 'cors' }
).then((res) => res.json())
// Take actual json
.then(({ response }) => appendData(response))
.catch(function (err) {
console.log(err)
});
}
function appendData(data) {
// clear previous research
document.getElementById("content").innerHTML = "";
let docs = data.docs;
// Take each element of the json file
for (elem of docs) {
var mainContainer = document.getElementById("content");
// title recipe
var a1 = document.createElement("a");
a1.setAttribute("href", elem.url);
var div = document.createElement("div");
div.innerHTML = elem.Title;
a1.appendChild(div);
// insert image of recipe and link for page in website
var a = document.createElement("a");
a.setAttribute("href", elem.Image);
var img = document.createElement("img");
// img.setAttribute("href", elem.url);
img.setAttribute("src", elem.Image);
a.appendChild(img);
// recipe description
var p = document.createElement("p");
p.innerHTML = elem.Description;
// Insert elements in dev
mainContainer.appendChild(a1);
mainContainer.appendChild(p);
mainContainer.appendChild(a);
}
}
function handler(event) {
if (event == "click") {
searchFile();
}
else if ((event.keyCode || event.which) == 13){
event.preventDefault();
event.cancelBubble = true;
event.returnValue = false;
event.stopPropagation();
event.preventDefault();
searchFile();
}
else {
console.log("Nothing")
}
}
What searchFile() and appendData() do is not important because they work. The target is when the user clicks on the search button or presses the enter key, searchFile() must be called. Clicking on the search button works, but the problem is when a user clicks enter, it navigates to http://localhost:8000/?search=SOMETHING (depends on what the user inserted) . I think it is the default behaviour of the enter key, I tried to prevent it using different codes but nothing works. I read that instead of using the event onkeypress we have to use onkeydown but I'm still in the same situation. I tried also to wait for the DOM to be loaded but nothing. Does someone have an idea about it?
Remove all the event handlers on the button
Make the button a submit button
Use the submit event on the form (this will trigger if the form submission is trigged by enter in the input or the button being clicked or enter being pressed over the button)
Prevent the default event behaviour (so the form data isn't submitted to a URL which the browser navigates to)
Don't bother doing any tests to try to figure out if it was a click or something else, all that matters if that the form was submitted.
const submitHandler = (event) => {
event.preventDefault();
alert("You can do your ajax search here");
};
document.querySelector('.example').addEventListener('submit', submitHandler);
<form class="example">
<input id="query" type="text" placeholder="Insert a recipe.." name="search" value="">
<button>Search</button>
</form>

Update a JS array value with a global variable based on checkbox (true/false) form input

I'm using a WorldPay JS function to create a payment form. This function creates a TOKEN that can be reusable or not. I need to update the 'reusable' flag based on a form input (checkbox) but I can't get the global variable (reuse) to update. I've created a function CHECKED that updates the variable but the WorldPay JS just ignores it. I think is due the window.onload status, but I don't know how to fix it. Any help would be greatly appreciated.
<?php
include('./header.php');
require_once('./init.php');
?>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type='text/javascript'>
var reuse = false;
function Checked(){
reuse = document.getElementById('check').checked;
Worldpay.submitTemplateForm();
}
window.onload = function() {
Worldpay.useTemplateForm({
'clientKey':'ENTER CLIENT KEY',
'form':'paymentForm',
'paymentSection':'paymentSection',
'display':'inline',
'type':'card',
'reusable': reuse,
'saveButton':false,
'callback':function(obj){
if (obj && obj.token && obj.paymentMethod) {
var _el = document.createElement('input');
_el.value = obj.token;
_el.type = 'hidden';
_el.name = 'token';
document.getElementById('paymentForm').appendChild(_el);
var _name = document.createElement('input');
_name.value = obj.paymentMethod.name;
_name.type = 'hidden';
_name.name = 'customer';
document.getElementById('paymentForm').appendChild(_name);
document.getElementById('paymentForm').submit();
}
}
});
}
</script>
</head>
<body>
<form action="./test.php" id="paymentForm" method="post">
<!-- all other fields you want to collect, e.g. name and shipping address -->
<div id='paymentSection'></div>
<div>
<input type="checkbox" id='check'>
<input type="submit" value="Place Order" onclick="Checked()" />
</div>
</form>
</body>
</html>
NOTE: I've removed the client ID so the code won't run.
Have you tried to use function "checked" on window.onload like this:
window.onload = function() {
Worldpay.useTemplateForm({
//code....
)}
function Checked(){
//code....
}

In an AMT HTML Questio. for batch, how to generate all inputs

So I've been trying to generate the contents mturk_form using the DOM model for a Amazon Mechanical Turk HTML question. I ran into an interesting error when I generated ALL inputs using the script: I get the error Dhtml template must contain a question.
This error can be hacked around by putting an unnamed hidden input in the top of the page, like the example below. Remove the <input type="hidden" /> and the error comes back. Does anyone have a better way?
<p><input type="hidden" /> <script>
window.onload = create_form;
function validate()
{
var checkbox = document.getElementById("testbox");
if (checkbox.checked)
{
return true;
}
else
{
alert("failed validation");
return false;
}
}
function create_form()
{
var turkform = document.forms[0];
var testbox = document.createElement('input');
testbox.type="checkbox";
testbox.name="testbox";
testbox.id="testbox";
testbox.innerHTML="check to be valid";
turkform.appendChild(testbox);
turkform.appendChild(document.createTextNode('check to be valid'));
var submitbutton = document.getElementById("submitButton");
submitbutton .onclick=validate;
turkform.appendChild(submitbutton);
}
</script></p>

On clicking the submit button it is not giving appropriate result

Hello ,
I am having some problem with javascript & Html..In my code i am reading excel file from directory and showing some output..for this i have a file input type and a Button...what is happening here is when i select the xls file and click on submit button Choose a file widow is opening every time when i am clicking on the submit button ..
the code is as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Speedometer HTML5 Canvas</title>
<script src="script copy.js"></script>
</head>
<body onload='draw(0);'>
<canvas id="tutorial" width="440" height="220">
Canvas not available.
</canvas>
<div>
<form id="drawTemp">
<input type="text" id="txtSpeed" name="txtSpeed" value="20" maxlength="2" />
<input type="button" value="Draw" onclick="drawWithInputValue();">
<input type=file id="fileInput" value="">
<input type=button value="submit" onclick="readdata(1,1);">
</form>
</div>
</body>
</html>
<script type="text/javascript" language="javascript">
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls", ".csv");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
// Use the <input type='file'...> object to get a filename without showing the object.
document.all["fileInput"].click();
var fileName = document.all["fileInput"].value;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open(fileName);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
}
catch (ex) {
alert(ex);
}
}
</script>
Every time i click on the submit button it opens the choose window to choose file ..why my button is behaving like file type input..
It's opening the "choose file" dialog because of this line in your Javascript:
document.all["fileInput"].click();
If you remove that, you won't get this behaviour.
document.all["fileInput"].click();
when you click on submit this line in the readdata() function is programmatically clicking on the choose file button.

Cant remove childnode without making childNode (message) not showing at all

I've have tried alot of different ways with removing the child and nothing has worked so faar, well it has to some degree, either i have no messages or i keep getting message that just add to the span without deleting the other
Tried reading up on how to remove the child, and have tried every different ways i've found to remove it, my code might be wrong on creating the child and append it etc. since it's the first time i use this way. Been trying with a while loop to remove, and the one that is already outcommented in the code, and with firstChild. and with different names instead of msg.
My code looks like this in my script:
function validateName(input, id)
{
var res = true;
var msg = document.getElementById(id);
var error = document.createElement("span");
var errorMsg = "";
if (input == "" || input < 2) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Input is to short!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && input.match(/\d/)) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Name contains a number!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && !input.match(/\d/)) {
res = true;
// removeChildren(msg);
}
return res;
}
My small test page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(e,id) {
if(validateName(document.form1.namefield.value, id) == false) {
document.getElementById("be").src="NotOkSmall.jpg";
}
if(validateName(document.form1.namefield.value) == true) {
document.getElementById("be").src="OkSmall.jpg";
}
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeydown="v1(be, div1)" >
<image id="be" src="NotOkSmall.jpg" alt="OkSmall.jpg" />
</div>
<input type="button" value="GO" onClick="v1(be)">
</form>
</body>
</html>
If anyone have any ideas to make it work I for one, would be a very happy guy :), as i have said before i am not even sure the creation of child is the correct way in this case. but as it works when i have removed removeChildren, it does write the correct messages, just dont delete any of them. So something must work..
Thanks.
You had some errors in your code like id.appendChild(error); where you had to use msg.appendChild(error);. Anyway I don't see a need to append/remove child nodes in this case. Just use hidden error placeholder and show it when you want to display an error message.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(imgId) {
var img = document.getElementById(imgId),
val = document.form1.namefield.value;
img.src = img.alt = validateName(val)
? "OkSmall.jpg"
: "NotOkSmall.jpg";
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeyup="v1('be');" >
<image id="be" src="NotOkSmall.jpg" alt="NotOkSmall.jpg" />
<span id="error-message" class="invis"></span>
</div>
<input type="button" value="GO" onClick="v1('be');">
</form>
</body>
</html>​​​​​​​​​
CSS:
​.invis {
display: none;
}​
JavaScript:
function validateName(input) {
var res = true,
errorMsg,
errorContainer = document.getElementById('error-message');
if(input.length < 2) {
res = false;
errorMsg = "Input is to short!";
}
if(input.length >= 2 && /\d/.test(input)) {
res = false;
errorMsg = "Name contains a number!";
}
if(res) {
errorContainer.style.display = 'none';
} else {
errorContainer.innerHTML = errorMsg;
errorContainer.style.display = 'inline';
}
return res;
}​
DEMO

Categories

Resources