I am trying to create a text-based adventure game. I managed to figure out how to make text output in html's textarea through simple onclick button, but now I am trying to do something new. I am having trouble with doing same thing but with input text where users can write anything in the box and then click on the button. Right now, I am trying to make this program to check the user input against some flag (in this case, I set my flag equal to 'pizza') before it does something. Unfortunately, my code doesn't work at all. I think I don't completely understand how the input is being passed around in JavaScript's functions.
The JavaScript part:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
if (fileName == "pizza") {
var obj=document.getElementById(test);
obj.value="is this showing up in the textarea???";
}
else {obj.value="wrong password!"; }
}
The html part:
<input name="filename" id="filename" type="text">
<a id="record_button" onclick="record('textarea1');" href="javascript:void(0);" title="Record">Perform Action</a>
<textarea wrap="virtual" cols="73" rows="10" id="textarea1"></textarea>
The problem is this block with your else statement, obj isn't declared. Because you have obj defined in the if statement above it is exclusive to that scope. Just define obj right above the if block.
--
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj=document.getElementById(test);
if (fileName == "pizza") {
obj.value="is this showing up in the textarea???";
}
else {
obj.value="wrong password!";
}
}
Add an event listener using JS:
document.getElementById('record_button').onclick=function(){
record('textarea1');
}
Also, there were a couple things wrong with your function. Here it is with corrections:
function record(test) {
var input = document.getElementById('filename');
fileName = input.value;
var obj = document.getElementById(test);
if (fileName == "pizza") {
obj.value = "is this showing up in the textarea???";
}
else {
obj.value = "wrong password!";
}
}
You were using document.getElementByID on the second line, which is incorrect capitalisation
You were only defining obj conditionally, so the else clause always threw an exception.
Here is a demonstration: http://jsfiddle.net/uQpp7/1/
Related
Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).
The code is suppose to validate an input and then execute a function when a button is clicked, but it is not working and the console does not suggest why. The only difference is that when you take away toString() on input it says it is not a function.
This is my first big project at university and not really sure which part is wrong?
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
const trimmed = input.toString().trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}
Function to be executed
function addRow() {
something...
}
validating if this function is true then execute this function.
function validate(){
if(check()){
addRow();
}
}
document.getElementById('input').addEventListener('input', check);
document.getElementById('btn').addEventListener('click', validate);
Html
<input type="text" id="input" class="input" autofocus autocomplete="off" placeholder="Add items in your list..">
<button id='btn' class="add">+</button>
Although the input variable is not declared in your code, I assume that it is supposed to represent the <input type="text"> element.
With the validation step you should validate the value of the input, not the input itself.
But your logic is still missing something. The else statement will never be reached. If the value is empty then the state will be set to '' and the function is stopped. If there is a value, and it has been trimmed, then you're always left with a string with a value in it and there for your value is truthy. So the else would not make without an if statement which would allow the value to be false when the validation is incorrect.
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
// Trim the value.
const trimmed = value.trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}
I'll start by saying that I have no idea why this is happening, and that just yesterday it was working just fine. I have this input (it gets saved on the Onblur event), and I can edit everything in the input except the final two characters or numbers in any field. It is though that is fixed for some reason. I don't seem to recall this happening before this morning. So I'm expecting Rod Serling to come in at any moment and inform me that I am in fact in the twilight zone. I've switched back to any earlier commit, when I new it was working, and for some reason the problem persists. (Even after a hard refresh and flushing content just in case JS is stale). Everything else works, on blur the values are saved correctly, it's just the simple fact that I CAN'T CHANGE THE LAST TWO CHARACTERS IN THE INPUT FIELD!!! (sorry, it was a late night)
EDIT: Sorry, I should state that it starts out like this:
<td onclick="addInput(this);" id="website_revenue:2017-03-16">$479,432.00</td>
And the input is added just fine.
If the value in the input is this:
<input type="text" id="input:website_revenue:2017-03-06" value="$479,432.00" />
I can't edit the "00".
I first thought, maybe it's a decimal issue, but I can't edit the last two characters in a whole number:
<input type="text" id="input:website_revenue:2017-03-06" value="360">
In that case I can't edit the "60".
Maybe it's my entire lack of sleep, but I've never seen anything like this before in my 15 years of programming...and I have NO IDEA why it's happening. No clues in the console, no errors are being flagged. Any ideas? Am I in the twilight zone??
Here is the JS being used, which again, worked just fine yesterday:
function addInput(elm) {
if (elm.getElementsByTagName('input').length > 0) return;
var value = elm.innerHTML;
elm.innerHTML = '';
var id = elm.getAttribute('id');
if(value == "$0.00" || value == "0"){
value = "";
}
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('id', 'input:'+id);
input.setAttribute('value', value);
input.setAttribute('style', 'width:100px;');
input.setAttribute('onBlur', 'closeInput(this)');
elm.appendChild(input);
input.focus();
}
function closeInput(elm) {
var td = elm.parentNode;
var value = elm.value;
td.removeChild(elm);
if(value == ""){
td.innerHTML = "0";
}else{
$.ajax({
type: "GET",
url: "/pages/process.php",
data: "edit_data="+elm.id+"&value="+value,
dataType: 'json',
success: function(ret){
if(ret.success === true){
td.innerHTML = ret.value;
if(ret.math === true){
var targets = ret.targets;
for (i in targets){
for (key in targets[i]){
if(key == "key"){
var newid = targets[i][key];
}
if(key == "value"){
var newval = Math.round(targets[i][key]);
var elm = document.getElementById(newid);
elm.innerHTML = newval;
}
}
}
}
}else{
$("#error").html("ERROR: These fields can only accept numbers!!");
td.innerHTML = "ERROR";
}
}
});
}
}
Ok, so I think I figured it out in github from a diff. The only real change was in CSS. The input seems to be inheriting a recent change to the div that contains the table, that sets the scroll from right to left (direction:rtl;), this set the cursor all the way to the right, and for some reason, that creates this issue. If I set the input itself to direction:ltr; the problem is fixed.
So I wonder, why does direction:rtl ruin the input?
So I'm unable to register for change or input events that allow me to grab the data that was just changed and apply it somewhere else...
document.getElementById("fI").addEventListener("input", blabla);
function blabla() {
var something = document.getElementById("fI").innerHTML;
document.getElementById("example2").innerHTML = something+" continue the rest of the script here";
}
This code doesn't execute and I can't figure out why from the documentation...
Edit:
This is the only HTML on the page, I'm debugging this right now
<textarea id="fI"></textarea>
<button type="button" id='pressMe'>Press Me</button>
<textarea id="example2"></textarea>
I've also used <p> for the recipient of the changed innerHTML
I've tested this code all on it's own, just like this, and it didn't work, however I'm trying to connect the code to this event listener too
document.getElementById("pressMe").addEventListener("click",doSomething);
function doSomething () {
var something = prompt("Please enter something", "something");
if (something !== null) {
document.getElementById("fI").innerHTML = something;
}
}
Use .value to get/set the contents of a textarea element. You were using .innerHTML.
document.getElementById("pressMe").addEventListener("click", doSomething);
function doSomething() {
var something = prompt("Please enter something", "something");
if (something !== null) {
document.getElementById("fI").value = something;
}
}
document.getElementById("fI").addEventListener("input", blabla);
function blabla() {
var something = document.getElementById("fI").value;
document.getElementById("example2").value = something;
}
<textarea id="fI"></textarea>
<button type="button" id='pressMe'>Press Me</button>
<textarea id="example2"></textarea>
you are not retrieving the value of your textarea correctly. you should be using .value instead of .innerHTML
var something = document.getElementById("fI").value;
http://jsfiddle.net/6pL8qony/
I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}