Javascript 2 clicks for onclick - javascript

I have a problem with the following javascript code. When I'm executing it from an onClick, it needs 2 clicks.
What I want to do is to click only once to display the books.
I have added the full code.
<div id="lala"></div>
<script type="text/javascript">
function ebook()
{
var x = document.getElementById('filetosearch').value;
var bt = document.createElement("script");
var lala = document.getElementById("lala");
var btt = document.createAttribute("src");
btt.value = "http://s1.interinfo.ro/hackyard/f.php?carte=" + x;
bt.setAttributeNode(btt);
lala.appendChild(bt);
if(error==1)
{
document.getElementById("cont").innerHTML="The minimum length is 3 characters.";
}else if(error==2){
document.getElementById("cont").innerHTML = "The book was not found.";
}else{
var output="<i>Found "+books+" books matching your query.</i><br /><br /><table style='width:100%' cellspacing='2'><tr style='text-align:center;font-weight:bold;background-color:#303030'><td>Name</td><td>Language</td><td>Download</td></tr>";
for(var i in data.books){
output+="<tr><td>" + data.books[i].name + "</td><td style='text-align:center'>" + data.books[i].lang + "</td><td><a href='" + data.books[i].download + "'>Download</a></td></tr>";
}
output+="</table>";
document.getElementById("cont").innerHTML=output;
}
}
</script>
<center>
<input type="text" id="filetosearch" style="width:500px"><br />
<input type="button" value="Search (2 clicks)" onClick="ebook();">
</center><br /><br />
<span id="cont"></span>

Because the append script runs async, global variable error is undefined until you get the response from the server.
You should put your process block of code in the onload event of bt script element like this,
bt.onload = function () {
if(error==1)
{
// code
}
// more code
}
a working example can be found here :
http://jsfiddle.net/Rad3q/

You mean the user has to double click the button instead of 1 click?
<input type="button" value="Search (2 clicks)" ondblclick="ebook();">

Related

Javascript - radio buttons onlick not working

I am stuck with a problem. I want to add call functions based on selection in radio button. But one of radio buttons doesn't work at all (not calling the function), other is not checked when clicked. Here is my code:
function clearElement(element_id){
document.getElementById(element_id).remove();
}
function createCheck(){
if (!document.getElementById('check')){
var btn = "<button onclick=\"checkData()\" id='check'>Check</button>";
document.getElementById("added").innerHTML += btn;
}
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type=\"radio\" value='Auto' id='auto' name=\"auto_manual\">I have ID</input>";
var added2 = "<input type=\"radio\" value='Manually' id='manual' name=\"auto_manual\"> Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete=\"on\"></input><br>";
var added5 = "<button onclick=\"fillIn()\">Continue</button>";
document.body.innerHTML += "<div id=\"added\">" + added0 + added1 + added2 + added3 + added4 + added5 + "</div>";
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.onclick = function() { createCheck();};
f1.onclick = function() { clearSelect('check');};
}
I want it to work the following way: if a user chooses "I have ID" option, the radio button is checked and the button "Check" will be created. If "Enter data manually", the button "Check" will disappear if exists.
Could you, please, help me with it?
Update (HTML):
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<title>Demo Web App</title>
</head>
<body>
<h1>Template Creator Bot</h1> <br> <br>
<script>
...
</script>
<div id='change'>
<select name="docs" id="selectedTemplate">
<option value="Order">Order</option>
<option value="Complaint">Complaint</option>
<option value="Other">Other</option>
</select>
<button onclick="addElements()">Next</button>
</div>
</body>
</html>
It would be better if you made the button element once and just toggled its visibility on demand.
There are also better strategies to compose dynamic html on your DOM instead of using innerHTML like using <template> or creating elements with document.createElement().
By the way, addressing specifically your issue here, I made a demo that adds the button in the main addElements() routine, and two functions: showButton() and hideButton() that will be called by the click event handlers added to the two radio options.
addElements();
function showButton(){
const target = document.getElementById('check');
if (target.classList.contains('hide'))
target.classList.remove('hide');
}
function hideButton(){
const target = document.getElementById('check');
if (!target.classList.contains('hide'))
document.getElementById('check').classList.add('hide');
}
function addElements(){
var added0 = "<p>Choose the filling method:</p><br>";
var added1 = "<input type='radio' value='Auto' id='auto' name='auto_manual'>I have ID</input>";
var added2 = "<input type='radio' value='Manually' id='manual' name='auto_manual'>Enter data manually</input><br>";
var added3 = "<p>Identification Code</p><br><input type=text id='ID'><br>";
var added4 = "<p>Enter your email address:</p><br><input type='email' id='mail' autocomplete='on'></input><br>";
var added5 = "<button onclick='fillIn()'>Continue</button>";
var added6 = "<button class='hide' onclick='checkData()' id='check'>Check</button>";
document.body.innerHTML +=
"<div id='added'>" + added0 + added1 + added2 + added3 + added4 + added5 + added6 + "</div>";
/*
Here adding the click event listener for the two radio options..
in the rest of your generated html you used the approach of defining handlers on html
so it's not clear why here you opted to do it programmatically for the radio options..
Anyway I only slightly changed the approach using addEventListener instead.
*/
var f0 = document.getElementById('auto');
var f1 = document.getElementById('manual');
f0.addEventListener('click', function() { showButton();});
f1.addEventListener('click', function() { hideButton();});
}
.hide{
display: none;
}
input[type=radio]{
cursor: pointer;
}

How do I target specific inputs on a form fields to change output to Title Case?

On my form I am trying to have specific output fields and their strings output as Title Case. May be worth noting, this form outputs to results on the same page. Here's a Fiddle demo of my form.
As you can see from it I have 3 input categories Name, City and Words, for this example I am trying to implement the Title Case script to just the 'Name" and City" output strings without it effecting the "Words" category. As I don't want to convert an ongoing sentence to Title Case.
I found a lot of discussion here on how to convert to title case. However I am having difficulty implementing this in to my form as I am still new to JavaScript. All the examples show the script, but not how to implement it in a form.
I was playing around with Greg Dean's top answer to try and target the specific inputs like so...
toTitleCase = function(str)
{
var name = document.getElementById('name');
var city = document.getElementById('city');
return str.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
However this does not seem to be working.
Here's the HTMl:
<form>
<input type="text" class="text" id="name" placeholder="Name">
<br>
<input type="text" class="text" id="city" placeholder="City">
<br>
<textarea type="textarea" id="words" placeholder="Words" cols="70" rows="6">
</textarea>
<br>
<input type="button" value="Combine" onclick="convert()">
<br>
<div class="wrap"><span id="CharCountLabel1" class="counter"></span>
<textarea type="textarea" name="output" id="output" cols="70" rows="10"
maxlength='' placeholder="Output"></textarea>
</div>
<br>
<button type="reset" onclick="ResetForm();" value="Reset
form">Reset form</button>
</form>
And the rest of the script:
function convert() {
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
var words = document.getElementById("words").value;
//input = wordwrap(input, 70, true);
var output = "";
if(!document.getElementById("name").disabled){
output += "Name: " + name + "\n";
}
if(!document.getElementById("city").disabled){
output += "City: " + city + "\n";
}
if(!document.getElementById("words").disabled){
output += "The words are... " + words + "\n";
}
document.getElementById("output").value = output;
}
CharacterCount = function(output,FieldToCount){
var myField = document.getElementById(output);
var myLabel = document.getElementById(FieldToCount);
var Chars = myField.length;
if(!Chars){Chars = "" ; };
var remainingChars = Chars + myField.value.length
myLabel.innerHTML = remainingChars+""+Chars
}
setInterval(function(){CharacterCount('output','CharCountLabel1')},55);
How do I target the script to just the specified input fields? Please no jQuery, just JavaScript solutions.
While you have a fully-function toTitleCase() function, you're never actually calling it. All you need to do is run your name and city variables through your toTitleCase function when you go to output them to the page:
if (!document.getElementById("name").disabled) {
output += "Name: " + toTitleCase(name) + "\n";
}
if (!document.getElementById("city").disabled) {
output += "City: " + toTitleCase(city) + "\n";
}
To prevent the words from also being transformed, simply don't pass that variable to the function:
if (!document.getElementById("words").disabled) {
output += "The words are... " + words + "\n";
}
A working demo of this can be seen here.
Hope this helps! :)

onClick Button Only Works Once

I have a button that checks input text to see if it is the right password. The problem is that the button only works once and when you click multiple times it doesn't run the function over and over again.
My Code:
<html>
<head>
<title>Password</title>
<script>
function passcheck() {
var attempts = 5;
var q = document.getElementById('txt').value;
if (q == "12345") {
document.getElementById("result").innerHTML = "You're In!";
} else {
attempts--;
document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!";
}
}
</script>
</head>
<body>
<font face="Verdana" size="5"><b>Enter Your Password:</b></font>
<br/><br/>
<input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25">
<button type="button" onclick="passcheck()">Submit!</button>
<p id="result"></p>
</body>
</html>
It is being called multiple times, but you aren't seeing a change because attempts is defined inside of the function. That means that every time you run that functions, attempts is being reset to 5. To fix that, move the attempts declaration outside of the function.
var attempts = 5; // Moved to here so we don't reset the value
function passcheck() {
var q = document.getElementById('txt').value;
if (q == "12345") {
document.getElementById("result").innerHTML = "You're In!";
} else {
attempts--;
document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!";
}
}
<font face="Verdana" size="5"><b>Enter Your Password:</b></font>
<br/>
<br/>
<input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25">
<button type="button" onclick="passcheck()">Submit!</button>
<p id="result"></p>
You are initializing the value of "attempts" and decrementing it every time you call the function. Hence it seems like the function is being called only once.
Move the deceleration of the variable outside the function. Something like
var attempts = 5;
function passcheck() {
//code here ...
}
Another slightly better way would be to make use of localStorage or sessionStorage or even using cookies.
Thanks,
Paras

How Would I program my Tic Tac Toe A.I. to only choose blank boxes?

I've made a Tic Tac Toe game using javascript, and I've made my an a.i., that selects random boxes on its turn. However, it may choose the same box twice or even a box which the player (which is X) has chosen. Here is the code:
<!DOCTYPE html>
<html>
<body>
<input type="button" id="k1" value=" " onclick="tictactoe(this)">
<input type="button" id="k2" value=" " onclick="tictactoe(this)">
<input type="button" id="k3" value=" " onclick="tictactoe(this)">
<br />
<input type="button" id="k4" value=" " onclick="tictactoe(this)">
<input type="button" id="k5" value=" " onclick="tictactoe(this)">
<input type="button" id="k6" value=" " onclick="tictactoe(this)">
<br />
<input type="button" id="k7" value=" " onclick="tictactoe(this)">
<input type="button" id="k8" value=" " onclick="tictactoe(this)">
<input type="button" id="k9" value=" " onclick="tictactoe(this)">
<br />
<script>
var nummoves=0;
var nummoves1=1;
var nummoves2=2;
var nummoves3=3;
var nummoves4=4;
var nummoves5=5;
var nummoves6=6;
var nummoves7=7;
var nummoves8=8;
var nummoves9=9;
var comp;
function tictactoe(square)
{
var check=["c1","c2","c3","c4","c5","c6","c7","c8","c9"]
check[0]=document.getElementById("k1");
check[1]=document.getElementById("k2");
check[2]=document.getElementById("k3");
check[3]=document.getElementById("k4");
check[4]=document.getElementById("k5");
check[5]=document.getElementById("k6");
check[6]=document.getElementById("k7");
check[7]=document.getElementById("k8");
check[8]=document.getElementById("k9");
comp=check[Math.floor(Math.random()*check.length)];
if(nummoves==0)
{
square.value="X";
}
if(nummoves1==1)
{
comp.value="O";
}
if(nummoves2==2)
{
square.value="X";
}
if(nummoves3==3)
{
comp.value="O";
}
if(nummoves4==4)
{
square.value="X";
}
if(nummoves5==5)
{
comp.value="O";
}
if(nummoves6==6)
{
square.value="X";
}
if(nummoves7==7)
{
comp.value="O";
}
if(nummoves8==8)
{
square.value="X";
}
if(nummoves9==9)
{
comp.value="O";;
}
}
</script>
</body>
</html>
So how would I change this code (but not entirely!), so that the a.i. knows only to choose a blank box?
Also, it it possible to make a clever A.I., e.g. it can block the player from getting three in a row, or even try to get three in a row itself.
Keep track of the marks made (perhaps in an array) and have the script check the array to see whether the spot is empty before marking it; if it's not empty the script would need to pick a different spot.
Or add this in place of comp=check[Math.floor(Math.random()*check.length)]:
var checking = true; // use this for the loop condition
while (checking)
{
comp = check[Math.floor(Math.random()*check.length)];
if (comp.value == " ") // check to see that the square is empty
{
checking = false; // if so, set the loop condition to false so the loop ends
}
}
Did this very quickly. The only thing that changes is the code in <script> and remove onclick attributes. Read comments in code to see what happens.
var squares = [], i = 10, move_number = 1;
while(--i) // build array of choices
squares[i-1] = document.getElementById('k'+i), // put square in array
squares[i-1].addEventListener('click', function () {tictactoe(this);}, false); // attach click listener
// `squares` keeps track of available squares
function randomSquare() { // A.I. square chooser
var i = Math.floor( Math.random() * squares.length ),
e = squares[i];
squares.splice(i,1); // remove choice from available
return e;
}
function tictactoe(square) { // passing `this` as first arg
var i;
square || (square = randomSquare()); // if no arg
if (move_number % 2) {
i = squares.indexOf(square);
if (i === -1) return; // square taken, do nothing
else squares.splice(i,1); // remove square from available
square.value="X";
++move_number;
tictactoe(); // A.I. turn
} else {
square.value="O";
++move_number;
}
}
Example fiddle.

JavaScript appendChild() not working? (first time with appendChild())

I am trying to build a little resume builder. I want the user to be able to enter any number of phone numbers. However, the appendChild() is not working as expected. Actually, it's not working at all. It does nothing. Any ideas?
HTML:
<div id="phoneNumbers">
<?php
if(isset($_SESSION['phoneNumber'])){
for($i = 0; $i<sizeof($_SESSION['phoneNumber']); $i++){
echo "<input type=\"text\" size=\"20\" name = \"phoneNumber[".$i."]\"
value=\"".$_SESSION['phoneNumber'][$i]."\" />
<br />";
}
}
else{
?>
<input type="text" size="20" name = "phoneNumber[0]"
value="" />
<br />
<?php
}
?>
</div>
<input type="button" value="Add another phone number" onclick="addPhoneNumber()">
Javascript:
var numberOfPhoneInputs = 1;
function addPhoneNumber()
{
// Found out the following doesn't work as expected...
// var newPhoneNumberInput = "<input type=\"text\" size=\"20\" name = \"phoneNumber[" +
// numberOfPhoneInputs +"]\" value=\"\" />" +
// "<br />"
// document.getElementById("phoneNumbers").innerHTML += newPhoneNumberInput;
var div = document.getElementByID("phoneNumbers");
var newPhoneNumberInput = document.createElement('input');
newPhoneNumberInput.setAttribute('type', 'text');
newPhoneNumberInput.setAttribute('name', 'phoneNumber['+numberOfPhoneInputs+']');
newPhoneNumberInput.setAttribute('size', '20');
newPhoneNumberInput.setAttribute('value', '');
div.appendChild(newPhoneNumberInput);
numberOfPhoneInputs ++;
}
document.getElementByID needs to be document.getElementById
This error should show in your console.
You need to return false; from the click handler to prevent the button's default action of submitting the page.
you need to make these changes ...
change document.getElementByID("phoneNumbers"); to document.getElementById("phoneNumbers");
(optional) It will be good if you change var div to var phoneNumbersDiv or something
fiddle example : http://jsfiddle.net/v8rF3/
Updated code:
var numberOfPhoneInputs = 1;
function addPhoneNumber(){
var div1 = document.getElementById("phoneNumbers");
var newPhoneNumberInput = document.createElement('input');
newPhoneNumberInput.setAttribute('type', 'text'); newPhoneNumberInput.setAttribute('name', 'phoneNumber['+numberOfPhoneInputs+']');
newPhoneNumberInput.setAttribute('size', '20');
newPhoneNumberInput.setAttribute('value', '');
div1.appendChild(newPhoneNumberInput);
numberOfPhoneInputs ++;
}

Categories