Error with <input> triggerWord and Javascript - javascript

I want to load the page http://example.com by typing trigger in the <input> text box. I made some modifications over time, and at some point it seemed to work but now it doesn't.
How can I make this work? What are some errors that I am missing?
window.onload = function() {
var input = document.getElementById("idname").focus();
}
$(function() {
var triggerWords = ['trigger'];
$('#indexinput').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>

You are registering on keyup two times, following code will work. Dont need to register it with javascript if you are mentioning it inline HTML.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" onkeyup="myFunction(event)" autofocus>
<script>
window.onload = function() {
var input = document.getElementById("idname").focus();
}
function myFunction(event) {
var triggerWords = ['trigger'];
for (let i = 0; i < triggerWords.length; i++) {
if (event.target.value == triggerWords[i]) {
window.open("http://example.com/", "_self");
break;
}
}
}
</script>

You have the wrong id in the query selector. It says
$('#indexinput') but must be $('#idname').
Consider using the following snippet:
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() == triggerWords[i]) {
console.log('open new page');
window.open("http://example.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>
Note that the window.open doesn't work in code-snippets, therefore I added the console.log part.
I also removed this unnecessary part:
window.onload = function() {
var input = document.getElementById("idname").focus();
}

There is no need of myFunction and id was incorrect
$(function() {
var triggerWords = ['trigger'];
$('#idname').keyup(function() {
for (var i = 0; i < triggerWords.length; i++) {
if ($(this).val() === triggerWords[i]) {
window.open("https://google.com/", "_self");
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idname" type="text" size="20" autofocus>

Related

Adding space after every 3rd number in input

I want to add space after every 3rd number, but this code doesn't work if the input is type="number". Does someone know how to modify the code to make it work even for type="number"
? Here is my input:
<input type="number" id="phone" autocomplete="off" placeholder="(+420)">
And also here is the script:
<script>
document.getElementById('phone').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{3})/g, '$1 ').trim();
});
</script>
Try this:
function insertBlankAfterEveryThreeCharacters(str) {
var str=str.split(" ").join("").split("");
var formatted=[];
while(str.length) {
for(var i=0; i<3 && str.length; i++) {
formatted.push(str.shift());
}
if(str.length) formatted.push(" ");
}
return formatted.join("");
}
Use in your event:
this.value=insertBlankAfterEveryThreeCharacters(this.value);
document.getElementById('phone').addEventListener('input', function (e) {
this.value=insertBlankAfterEveryThreeCharacters(this.value);
});
function insertBlankAfterEveryThreeCharacters(str) {
var str=str.split(" ").join("").split("");
var formatted=[];
while(str.length) {
for(var i=0; i<3 && str.length; i++) {
formatted.push(str.shift());
}
if(str.length) formatted.push(" ");
}
return formatted.join("");
}
<input id="phone">
<input type="number"... makes it so you can go up/down one = I assume not an intended result...
Your place holder has parentheses and a plus in it - It is not what you seem to be wanting in the solution...

implementing insertbefore() in loop

I am trying to show error messages below an array of textboxes that I have selected using Javascript. The error messages are being put by creating a new span element and using the insertBefore() method. The span element is created in the function since I don't want to hard code it into the DOM. The span messages do show but each time I submit the form, they are appended over and over again. I'd like to show the span messages only once and each time the form is submitted, they are shown once only. Below is my code.
HTML
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" />
<input type="text" name="2" class="textbox" />
<input type="text" name="3" class="textbox" />
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
JAVASCRIPT
<script>
var slideshow = document.querySelector('.slideshow');
// var span = document.createElement('span');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function(e)
{
e.preventDefault();
for( var i=0; i<inputs.length; i++ )
{
var span = document.createElement('span');
(function(index)
{
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
</script>
Each time I submit, I'd like the error messages to be shown below the textbox and not appended over and over again. They should be shown just once and I'd like to do this without using jQuery or any sort of library.
I rewerite your example to create available 3 span tags instead of crate them in code. If there are some errors, populate them to span rather than creating/deleting the spans in code.
var slideshow = document.querySelector('.slideshow');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
(function (index) {
document.getElementsByTagName('span')[index]
.innerHTML = 'error ' + index;
})(i);
}
}, false);
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" /><span></span>
<input type="text" name="2" class="textbox" /><span></span>
<input type="text" name="3" class="textbox" /><span></span>
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
Hope this help.
Just do a check before you insert. Here is one way to do it.
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
if (inputs[index].nextElementSibling.tagName !== 'SPAN')
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
You have to wait for page to be load, the you should run JavaScript.
PageLoad Event : window.onload=function(){}
Code :
<script type="text/javascript">
window.onload = function () {
var slideshow = document.querySelector('.slideshow');
var form = document.getElementById('form');
var inputs = document.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
}
</script>
Put your code in window.onload event.

jQuery Counter Not Working

JavaScript/jQuery newbie here!
I have the following form here (using bootstrap's disabled class, heads up):
EDIT: the class 'disabled' is a thing in bootstrap, and does properly disable and enable the button if it is there or not.
<form action="" method="post">
<input type="text" id="bio">
<p class="bio-counter"></p>
<input type="text" id="username">
<p class="user-counter"></p>
<input type="submit" class="btn">
</form>
And the following script (I have included jQuery in my head tag correctly):
var main = function() {
$('.bio-counter').text('500');
$('.user-counter').text('0');
var postLengthUser = $('#username').val().length;
var postLengthBio = $('#bio').val().length;
$('#username').keyup(function() {
$('.user-counter').text(postLengthUser);
});
$('#bio').keyup(function() {
var charactersLeftBio = 500 - postLengthBio;
$('.bio-counter').text(charactersLeftBio);
});
if(postLengthUser > 6 && postLengthUser < 21) {
if(postLengthBio >= 0 && postLengthBio < 501) {
$('.btn').removeClass('disabled');
} else {
$('.btn').addClass('disabled');
}
} else {
$('.btn').addClass('disabled');
}
}
$(document).ready(main);
I am running into the following problems:
The 'btn' is not losing it's disabled state, even when I type enough information in the inputs.
The counters are not updating.
What am I doing wrong?
<script>
var main = function () {
var postLengthUser = 0;
var postLengthBio = 0;
$('.bio-counter').text(500);
$('.user-counter').text(0);
var validate = function () {
if (postLengthUser > 6 && postLengthUser < 21) {
if (postLengthBio >= 0 && postLengthBio < 501) {
$('.btn').removeClass('disabled');
} else {
$('.btn').addClass('disabled');
}
} else {
$('.btn').addClass('disabled');
}
}
$('#username').keyup(function () {
postLengthUser = $('#username').val().length;
$('.user-counter').text(postLengthUser);
validate();
});
$('#bio').keyup(function () {
postLengthBio = $('#bio').val().length;
var charactersLeftBio = 500 - postLengthBio;
$('.bio-counter').text(charactersLeftBio);
validate();
});
validate();
}
$(document).ready(main);
</script>
You're validating the disabled condition only at page load, it should be run at each keyup event - i moved it to validate function.
postLengthUser and postLengthBio were updated only at page load too. They should be updated on each key up event too.
Try using:
$('.btn').prop('disabled', true);
and
$('.btn').prop('disabled', false);
instead.

Hiding multiple form fields using checkboxes

I have this code that I need to edit so I can use it on multiple chkBox's and txtBox's.
Currently I can only hide one input field with one check box.
I know HTML and CSS but I am not familiar with JS.
I would like to be able to add a number at the end of each ID.
chkBox1, chkBox2, chkBox3... txtBox1, txtBox2, txtBox3...
Do I need to change getElementById to getElementsByTagName()?
JSFIDDLE for some reason it does not work here...?
This is my current code which hide the text field unless the checkbox is checked:
function showHide(){
var chkBox = document.getElementById("chkBox");
var txtBox = document.getElementById("txtBox");
if (chkBox.checked){
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}
The reason your code wasn't working is because it was running onLoad. Your DOM and the onclick were created before the load was complete. You could just move your code into your <head></head> tags and it will work as is. See here, all I did was select the "No wrap - in head", no code changes.
You could also continue to have your javascript run onLoad and remove your onclick and add an eventlistener in the javascript like this:
JSFiddle
var txtBox = document.getElementById("txtBox");
document.getElementById("chkBox").addEventListener("click", function() {
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
});
If you have multiple instances of this, I would change your DOM a bit sort of like this:
<form>
<div class="option">
<input type="text" name="txtBox1" class="hiddenInput" />
<br/>
<input type="checkbox" name="chkBox1" id="chkBox1" class="showHideCheck" />
<label for="chkBox1">Click me to show the text box</label>
</div>
<div class="option">
<input type="text" name="txtBox2" class="hiddenInput" />
<br/>
<input type="checkbox" id="chkBox2" name="chkBox2" class="showHideCheck" />
<label for="chkBox2">Click me to show the text box</label>
</div>
</form>
and do your JQuery like this (since you previously tagged jquery):
$(".hiddenInput").hide();
$(".showHideCheck").on("change", function() {
$this = $(this);
$input = $this.parent().find(".hiddenInput");
if($this.is(":checked")) {
$input.show();
} else {
$input.hide();
}
});
JSFiddle
Or with pure javascript and the similar DOM as above:
var checkBoxes = document.getElementsByClassName("showHideCheck");
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('click', function () {
var txtBox = getAssociatedTextBox(this);
if (this.checked) {
txtBox.style.visibility = "visible";
} else {
txtBox.style.visibility = "hidden";
}
}, false);
}
function getAssociatedTextBox(ele) {
var childNodes = ele.parentNode.childNodes;
for (i = 0, j = childNodes.length; i < j; i++) {
if (childNodes[i].className == "hiddenInput") {
return childNodes[i];
}
}
}
JSFiddle
Try this,
Javascript
$(document).ready(function(){
$("input[type=checkbox]").change(function(){
var oTxt = $("#txtBox" + $(this).attr("id").replace("chkBox", ""));
if($(this).is("checked"))
oTxt.show()
else
oTxt.hide();
});
});
HTML
<input type="checkbox" id="chkBox1"/>
<input type="textbox" id="txtBox1"/>
<input type="checkbox" id="chkBox2"/>
<input type="textbox" id="txtBox2"/>

input box not working in firefox

I am trying to have a basic filter when someone puts a word into a input box and list items hide on click, this is working fine in chrome but in firefox it is not working at all.
html:
<form ACTION="#" id="navsform" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search...">
<input type="submit" class="my-button" value="Search" onclick="query_searchvar()"></form>
javascript:
function query_searchvar()
{
var searchquery=document.navsform.query.value.toLowerCase();
if(searchquery == '')
{alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
if (found == true )
{
$(this).show("normal");
}
else {
$(this).hide("normal");
}
});
}
Any help much appreciated. Thank you.
Hi, I managed to get this working with a combo of all your comments and some jquery resources:
HTML:
<form id="myform" action="#" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search..." />
<input class="my-button" type="submit" value="Search" />
</form>
$('#myform').submit(function() {
var searchquery = String($('#myform input[name=query]').val()).toLowerCase();
if (searchquery == '') {
alert('No Text Entered');
}
var queryarray = searchquery.split(/,|\s+/);
$('li').each(function() {
var searchtags = $(this).attr('data-searchtags');
var searcharray = searchtags.split(',');
var found = false;
for (var i = 0; i < searcharray.length; i++)
if ($.inArray(searcharray[i], queryarray) > -1) {
found = true;
break;
}
if (found == true) {
$(this).show('normal');
}
else {
$(this).hide('normal');
}
});
return false;
});
document.navsform.query.value ???
onclick="query_searchvar()" ???
event.preventDefault ??? -- lack crossbrowser
Why Use click rather than submit?
missing return false?
why use it?
You're already using jQuery, it would be better to work 100% with Jquery?
<form ACTION="#" id="navsform" class="my-search">
<input id="formwidth" type="text" name="query" placeholder="Search...">
<input type="submit" class="my-button" value="Search"></form>
Javascript:
$(document).ready(function(){
$("#navsform").submit(function(event){
event = event||window.event; //Cross
var searchquery=String($("#navsform input[name=query]").val()).toLowerCase();
if(searchquery == ''){
alert("No Text Entered");
}
var queryarray = searchquery.split(/,|\s+/);
event.preventDefault();
$('li').each(function(){
var searchtags = $(this).attr('data-searchtags');
//alert(searchtags);
var searcharray = searchtags.split(',');
//alert(searcharray);
var found = false;
for (var i=0; i<searcharray.length; i++){
if ($.inArray(searcharray[i], queryarray)>-1) {
found = true;
break;
}
}
if (found == true ){
$(this).show("normal");
} else {
$(this).hide("normal");
}
});
});
return false;//prevents sending the form, remove if necessary.
});
There are a few things, you should change:
Pass in the event object to the handler function.
Attach the eventhandler to the form submit event, not the button. This way the return key will work.
Then you should use a tool like Firebug, Dragonfly or similar. It helps a lot. As mentioned in the comments, you could have found your error.
See Guilherme Nascimento's answer for an example. (But ignore the tone..)

Categories

Resources