Here is my code :
<form>
<input type="text" id="input"/>
<br/>
<div id="buttons">
<input id="search" onclick="search()" type="button" value="Search"/>
<input type="button" value="Random"/>
<script type="text/javascript">
function search() {
var search = document.getElementById('search');
var int = setInterval(function() {
if (search.value.length == 6) search.value = 'Searchi';
else if (search.value.length == 7)
search.value = 'Searchin';
else if (search.value.length == 8)
search.value = 'Searching';
else {
search.value = 'Search';
}
//clearInterval( int ); // at some point, clear the setInterval
}, 500);
}
</script>
</div>
</form>
the button function is not working when <form> element is in the code. by removing the form element you will see that the JavaScript works! I want to know what is the problem? and how can I fix it?
Also, is there a better code for the result that I want? Somebody told me that I am using an old method of JavaScript!
Change the element id-search which hides in IE the function search of the global object:
<input id="search" onclick="search()" type="button" value="Search"/>
Should be:
<input id="search-suffix" onclick="search()" type="button" value="Search"/>
P.S.
int is a reserved word in javascript though it doesn't do anything in the meanwhile, just like class and private etc', thus should be avoided.
Related
I am a total noob to web programming (Started just now). I know C, C++ and x86-assenbly (a little bit). I wanna create my own home page for my browser. It's very basic html for the most part but I want a search bar on the top that redirects to duckduckgo with relevant results and that's where the problem arises. The code I'm trying:
<form>
<input type="text" id="query"/>
<button id="button" class="button" onclick="openInDuck()">Search</button>
</form>
<script>
function openInDuck(){
var x= "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location = x;
}
</script>
And yeah, I forgot, I am using qutebrowser on archlinux if that matters. Thanks in advance.
You are missing .href on your redirect. Also you should change the button type to button instead of the default;
function openInDuck() {
var x = "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location.href = x;
}
<form>
<input type="text" id="query" />
<button id="button" class="button" onclick="openInDuck()" type="button">Search</button>
</form>
Do note that it wouldn't be ideal to redirect the user if you just need to do a search through a different api.
You can use the below
function openInDuck() {
var x="https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.open(x);
}
Problem is that your form is submitted when clicking the button, like this it works :)
<input type="text" id="query" />
<button id="button" class="button" onclick="openInDuck()">Search</button>
<script>
function openInDuck() {
var x = "https://duckduckgo.com/?q=";
x += document.getElementById("query").value;
window.location = x;
}
</script>
You are close to the solution. In the JS code, you must add .href after window.location to set the new href (URL) for the current window. In the HTML code, I suggest you use the onsubmit attribute to send the form with an input type="submit" :
function openInDuck()
{
var x = "https://duckduckgo.com/?q=";
x += document.getElementById('query').value;
window.location.href = x;
return false; // Prevent the form submission
}
<form onsubmit="return openInDuck()">
<input type="text" id="query">
<input type="submit" id="button" class="button" value="Search">
</form>
My code:
<?php
$id = 0;
/*if(isset($_POST["type_test"]) && !empty($_POST["type_test"])){
if($_POST["type_test"] == "ola"){
echo "Ola José";
}
else if($_POST["type_test"] == "adeus"){
echo "Adeus José";
}
else{
}
}*/
?>
<html>
<form id="<?php echo $id; ?>" name ="form_test" action = "test_form.php" method="post" >
<input type="radio" id = "type_test" name="type_test" value="ola"> ola <br>
<input type="radio" id = "type_test" name="type_test" value="adeus"> adeus <br>
<input type="submit" value="submit"> //imput only use for POST method
<button id="myBtn">Try it</button>
<script>
</script>
</form>
<script>
document.getElementById("myBtn").addEventListener("click", functio_test;
functio_test(){
var x =document.getElementById.("type_test").value;
if(x == "ola" ){
alert("Ola José");
}
else if(x == "adeus" ){
alert("Adeus José");
}
else
alert("Continua José");
}
</script>
</html>
This is a simple program for when a button is triggered, an alert message appears.
I tried with the POST method and it worked. Why does it not work with the DOM Event Listener?
Because you're not using it correctly. addEventListener should be called like this:
document.getElementById("myBtn").addEventListener("click", function(){
// code here
});
Or, you can call it like so:
document.getElementById("myBtn").addEventListener("click", functio_test);
// and you must make sure to declare your function correctly
function functio_test(){
// code here
}
Code should look like this
<form id="<?php echo $id; ?>" name ="form_test" action="test_form.php" method="post">
<input type="radio" name="type_test" value="ola"> ola <br/>
<input type="radio" name="type_test" value="adeus"> adeus <br/>
<input type="submit" value="submit" /> <!--imput only use for POST method-->
</form>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", functio_test);
function functio_test(){
var x = document.querySelector('input[name="type_test"]:checked').value;
if(x == "ola"){
alert("Ola José");
}
else if(x == "adeus"){
alert("Adeus José");
}
else {
alert("Continua José");
}
}
</script>
Comment for "imput only use for POST method" was not a real comment. As mentioned before by #Hossam you are missing a closing bracket in the addEventListeiner. As mentioned by #Cruiser you are missing the word function when declaring the function. Also an id attribute should be unique so id="type_test" should only be assigned once. The way to get the value of the type_test radio buttons can be done via query selector your id call did not work because you have to find the one that is checked. I assume you don't want to submit the form by clicking on the try it button. The easiest way is to put the button outside of the form.
Also check out the jQuery Javascript library which makes Javascript fun :)
make sure you close every bracket:
document.getElementById("myBtn").addEventListener("click", functio_test);
Why does it not work with the DOM Event Listener?
The call to addEventListener() is not closed.
document.getElementById("myBtn").addEventListener("click", functio_test;
To fix this, add a closing parenthesis:
document.getElementById("myBtn").addEventListener("click", functio_test);
// ^
See this working in the example below. Notice a few changes were made:
function keyword added before function name: function functio_test()
event argument accepted: function functio_test(e)
event default behavior (button click submitting form) stopped: e.preventDefault()
getting value from the form elements (instead of by id - since that only relates to the first input with that id attribute):
var x = document.forms[0].elements.type_test.value;
The <input> tags have no permitted content and thus are empty elements, so the closing slash was added to the end of the tags. For example:
<input type="radio" id="type_test" name="type_test" value="ola" />
// ^
The id attribute of the second radio button was changed because "The id global attribute defines a unique identifier (ID) which must be unique in the whole document."2
<input type="radio" id="type_test2" name="type_test" value="adeus" /> adeus <br>
Also if this code wasn't in the snippet sandbox, the <form> and <script> tags would be moved into a <body> tag under the <html> tag, since those are flow content and the only permitted contents for <head> are: "One <head> element, followed by one <body> element."1
Also the id attribute of the form has the text 'form` prepended because "Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility."3
document.getElementById("myBtn").addEventListener("click", functio_test);
function functio_test(e) {
e.preventDefault();
var x = document.forms[0].elements.type_test.value;
if (x == "ola") {
alert("Ola José");
} else if (x == "adeus") {
alert("Adeus José");
} else
alert("Continua José");
}
<form id="form0" name="form_test" action="test_form.php" method="post">
<input type="radio" id="type_test" name="type_test" value="ola" /> ola <br>
<input type="radio" id="type_test2" name="type_test" value="adeus" /> adeus <br>
<input type="submit" value="submit" /> //imput only use for POST method
<button id="myBtn">Try it</button>
</form>
1https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html)
2https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
3https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id)
I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle
I am trying to make a form with one text input and a submit button. What I want the script to do is take the text after I click submit and store it as a value. After that, if I type something else (without refreshing the page) and click submit store the input as another value. This process can be done one hunded times so I will have 100 different values. What I also want to do with this values is put them in a new array.So:
var AllValues = [""+Val1+"",""+Val2+"",""+Val3"",..,""+Val99+"",""+Val100""];.
The code I have managed to write untill now is this but it won't actually help you:
<!DOCTYPE html>
<html>
<body>
<form id="form1">
Type the words here: <input type="text" name="fname"><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<input type="button" onclick="myFunction2()" value="Print all inserted words at array">
<p id="demo"></p>
<script>
function myFunction() {
}
function myFunction2() {
var AllValues = [""+Val1+"",""+Val2+"",""+Val3"",..,""+Val99+"",""+Val100""];
document.getElementById("demo").innerHTML = AllValues;
}
</script>
</body>
</html>
I am asking this question after trying a lot of things which didn't worked and I know that the script will work only if I use HTML local storage but I don't have the knowledge to do it even if I did a lot of research on this topic. I dont want to only store the values but I want to get them inside a new Array. I am making the question a bit more general as always in order to help as many as possible. Could you please help me? Thanks in advance.
You had several issues, the main is that you have to provide the "id" attribute for the input text named "fname".
Next you have to store the AllValues array in context visible by two declared functions (in this case, the global context).
<!DOCTYPE html>
<html>
<body>
<form id="form1">
Type the words here: <input type="text" name="fname" id="fname"><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<input type="button" onclick="myFunction2()" value="Print all inserted words at array">
<p id="demo"></p>
<script>
var AllValues = [];
function myFunction() {
var fname = document.getElementById("fname").value;
AllValues.push(fname);
}
function myFunction2() {
document.getElementById("demo").innerHTML = AllValues;
}
</script>
</body>
</html>
Try also the immediate function to avoid storing variables in global context. The code that I paste is not very clean of course, but working :)
For a very basic way of doing this, try the following:
HTML:
<form id="form1">Type the words here:
<input type="text" name="fname">
<br>
<input type="button" value="Submit" class="submit">
</form>
<input type="button" class="show-button" value="Print all inserted words at array">
<p id="demo"></p>
JS:
var values = new Array();
$(".submit").on("click", function () {
values.push($('input[name="fname"]').val());
});
$(".show-button").on("click", function () {
$("#demo").html(values.join("<br>"));
});
Fiddle here: http://jsfiddle.net/5z4g04js/2/
My answer:
<form id="form1">
Type the words here: <input id="words" type="text" name="fname"><br>
<input type="button" id="submitWords" value="Submit">
</form>
<input type="button" id="printWords" value="Print all inserted words at array">
<p id="demo"></p>
<script>
var arrWords = [];
var btnSubmit = document.getElementById('submitWords');
var btnPrint = document.getElementById('printWords');
var demo = document.getElementById('demo');
btnSubmit.onclick = function() {
var words = document.getElementById('words').value;
arrWords = words.split(' ');
console.log(arrWords);
}
btnPrint.onclick = function() {
for(var i = 0; i < arrWords.length; i++) {
demo.innerHTML += arrWords[i]+"<br>";
}
}
</script>
</body>
</html>
You could use jquery to do that:
var all_values =[];
function myFunction() {
var temp_val = $("#fname").val();
alert(temp_val);
all_values.push(temp_val);
}
function myFunction2() {
alert(all_values);
}
<form id="form1">
Type the words here: <input type="text" name="fname" id="fname"><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<input type="button" onclick="myFunction2()" value="Print all inserted words at array">
<p id="demo"></p>
working demo
p.s. edited jquery answer with more changes. working demo
Using this getAllValues(name) function, you can return the values of any element with the name of 'name'.
function getAllValues(name) {
var nameMatches=document.getElementsByName(name);
var AllValues=[];
for (var i=0; i<nameMatches.length; i++) {
AllValues.push(nameMatches[i].name);
AllValues.push(nameMatches[i].value);
}
return AllValues;
}
To call this you would use getAllValues('fname').
I am using the jQuery Mobile and Phonegap to create a Study Timer and I am trying to change a form value through JS.
The form value:
<form action="javascript:void(null);" id="theTimer" name="theTimer">
<input id="timerDisplay" type='text' name="theTime" readonly/>
<br />
<input type='submit' name="start" value="Start" onclick="Start()"/>
<input type='submit' name="stop" value="Stop" onclick="Stop()"/>
<input type='submit' name="pause" value="Pause" onclick="Pause()"/>
</form>
The JS code:
function Pause() {
if (timerID) {
clearTimeout(timerID);
}
if (myTimer) {
clearInterval(myTimer);
}
if (document.theTimer.pause.value == "Pause") {
document.theTimer.pause.value = "Resume";
} else {
document.theTimer.pause.value = "Pause";
tToday = new Date();
total_time = tToday.getTime() - tDiff;
tStart = new Date(total_time);
timerID = setTimeout(UpdateTimer, 1000);
startTimer();
}
}
The problem is that when I was using another framework the form value Pause would change to Resume and Resume to pause through the Pause() function... now it doesn't see the Pause form value at all...
What am I missing to get to form value Pause to change to Resume?
If you are using jquery, you could be doing:
if ($('input[name=pause]').val() == "Pause") {
$('input[name=pause]').val("Resume");
}
instead of
if (document.theTimer.pause.value == "Pause") {
document.theTimer.pause.value = "Resume";
}
The scope of the variables within your function is confusing because you've omitted the var keyword on all of them. I would first clean up your variable declarations, and use the power of jQuery instead of manually fighting your way through the DOM to set values:
<form action="javascript:void(null);" id="theTimer" name="theTimer">
<input id="timerDisplay" type="text" name="theTime" readonly="readonly" />
<br />
<input type="submit" name="start" id="start" value="Start"/>
<input type="submit" name="stop" id="stop" value="Stop"/>
<input type="submit" name="pause" id="pause" value="Pause"/>
</form>
I removed your onclick events and fixed your readonly attribute, and your quotes. I think part of the problem is that you were submitting the form when clicking the buttons and the page was posting back. Your timers were resetting when this happened causing unexpected behavior. I'm adding back the functions using jQuery:
$(function() {
$('#start').click(function() {
Start();
return false;
});
$('#stop').click(function() {
Stop();
return false;
});
$('#pause').click(function() {
Pause();
return false;
});
});
var timerID, myTimer;
function Pause() {
if (timerID) {
clearTimeout(timerID);
}
if (myTimer) {
clearInterval(myTimer);
}
if ($('#pause').val() == "Pause") {
$('#pause').val("Resume");
} else {
$('#pause').val("Pause");
var tToday = new Date();
var total_time = tToday.getTime() - tDiff;
var tStart = new Date(total_time);
timerID = setTimeout(UpdateTimer, 1000);
startTimer();
}
}
Perhaps you could fill in the gaps in your question with what startTimer() and UpdateTimer() do? Also, you haven't really explained what your issue is exactly... could you indulge us?
Don't use submit buttons, use <input type="button" ...>. Your form is posting and returning a new page with the buttons in their default settings.
You can forget the xml-style markup, it's just wasted characters. And void is an operator, not a function, so you don't need to follow it with the grouping operator (). You don't need it anyway, the required action attribute can be anything, '#' is sufficient in this case - if the form isn't submitted, it won't go anywhere.
<form action="#" id="theTimer" name="theTimer">
<input id="timerDisplay" type="text" name="theTime" readonly>
<br>
<input type="button" name="start" value="Start" onclick="Start()">
<input type="button" name="stop" value="Stop" onclick="Stop()">
<input type="button" name="pause" value="Pause" onclick="Pause()">
</form>
By convention, identifiers starting with a capital letter are reserved for constructors and identifiers with all captial letters for constants.