Jquery Input Text - javascript

I have been searching for a similar question/answer and didn't see one. Apologies in advance if this is a duplicate.
I am creating a text-based game in JS. This is my 1st time creating a project from scratch. All the text happens in the #dialog div and I want to have the user input to correspond to if-else function choices and generate text in the for the new options.
I have the first transition(the text from intro game changes to the text in scene one when clicked)working. What is not working is the choice selection text input. Anything I enter refreshes the game. I also put in an alert to test it and that does not run.
Another question I have is if the variables for the new choices which I have put in the if/else statement will run as coded or if I need to make changes. Some options will occur more than once so I will want it to run from inside multiple scenes.
HTML
<div id="dialog">
</div>
<div class="form">
<form id="my-form">
<input type="text" id="userData" placeholder="enter move here">
<button type="submit" class="btn">play</button>
</form>
</div>
JS
// game dialog box / adds paragraph to the #dialog div
// User move - form input
var addParagraph = $('#dialog');
var userMove = $("#userData").val();
//intro game text
var introGame = $(function () {
$(addParagraph).append('<p> My Text.. </p>');
});
//1st scene of game. Player chooses 1,2 or 3. Choice triggers new text in dialog box and new set choices or player outcomes.
var scene1 = $(function () {
$(introGame).click(function() {
$(addParagraph).text('Move Question Text');
$(addParagraph).append("<p> 1.Choice Description </p>");
$(addParagraph).append("<p> 2.Choice Description </p>");
$(addParagraph).append("<p> 3.Choice Description </p>");
$(addParagraph).append("<p> Enter: 1, 2, or 3 below </p>");
var playMove = function() {
$("#my-form").submit(function() {
var text = userMove;
var move = template(text);
if(text == '') {
return false;
} else if(text == '1') {
$(scene1).click(function () {
evasiveManuevers();
});
}else if(text == '2') {
$(scene1).click(function () {
lightSpeed();
});
} else if(text == '3') {
$(scene1).click(function () {
fightEnemy();
});
} else {
alert("Working!");
}
});
};
});
});
Thank you in advance!

I guess what you are doing wrongly is expecting that this
var userMove = $("#userData").val();
will change during the game. $("#userData").val() is a value, not a function, so if I understand what you want correctly, you should create a getter like this
var getUserMove = function(){ $("#userData").val(); };
and use it as var text = getUserMove();. But it's not clear where your
var addParagraph = $('#dialog');
var userMove = $("#userData").val();
code is (is it inside some handler? I'd recommend to show the whole code as one script, not separate it into some parts).

I don't think your IF statements will run like that. You could do your IF condition testing inside your scene1 click function like this:
$(scene1).click(function (){
if(text == '1') {
evasiveManuevers();
} else {
if(text == '2') {
lightSpeed();
} else {
// etc
}
})

Related

How to hide the next button on qualtrics until a text field is filled in with text?

I have a survey with two questions on the page (one that is multiple choice) and one that is a text entry question.
I want to hide the next button until the text entry question has been filled out but I've only been able to hide the next button indefinitely and it seems to not reappear after the text field has been filled in.
Qualtrics.SurveyEngine.addOnload(function()
{
this.hideNextButton();
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {hideNextButton ()} else {showNextButton ()}
});
});
});
You have some syntax errors. It looks like you are trying to use jQuery instead of Prototypejs. Besides that, you need to restrict your input element search to the question and there is only one input field so you only need one function. Try this (edited to defer initial next button hide):
Qualtrics.SurveyEngine.addOnload(function() {
function hideEl(element) {
element.hide();
}
var nb = $('NextButton');
hideEl.defer(nb);
$(this.questionId).down('.InputText').on('keyup', function(event) {
if(this.value.length == 0) nb.hide();
else nb.show();
});
});

Hiding other elements by one input field

Please can you provide me some short help with my Javascript code. I have one input field which hides DIV element just if it is totally empty (without text):
if (search_value !== "") {
document.getElementById("frei").className = "frei1";
}
It does exactly what I want, the main problem is once the input field is activated by typing inside and when I start to erase the text until the input is empty, than my hidden DIV appear, even if the input contain no text (because I erased it). This function is good only on first page load, than when I type anything in input and erase it, my JavaScript code is not functional.
Please could you give me an advice how looks like Javasript code, which hide that DIV everytime input field contain no text? Even when the text was erased manually?
Thank you very much and apologize for that type of question. Iam not strong in basic Javascript.
That code will only execute on page load, yet you want it to run each time someone types into your input, to do that you can use the onkeyup event:
document.getElementById("yourInput").onkeyup = function () {
if (this.value !== "") {
document.getElementById("frei").className = "frei1";
}
else {
document.getElementById("frei").className = "";
}
};
DEMO
If you also need it to run on page load aswell however, extract it out to a function and then you can call the function on page load as well:
function setDisplay() {
if (document.getElementById("yourInput").value !== "") {
document.getElementById("frei").className = "frei1";
}
else {
document.getElementById("frei").className = "";
}
}
Then call it on page load:
setDisplay();
Then also attach it to the onkeyup event like we did in the first instance:
document.getElementById("yourInput").onkeyup = setDisplay;
document.getElementById("id").oninput = function() {
if (this.value !== "") {
document.getElementById("frei").className = "frei1";
}
}
or
document.getElementById("id").addEventListener('input',function() {
if (this.value !== "") {
document.getElementById("frei").className = "frei1";
}
}, false);

If a specific value is inputed into an input box, display a message using javascript

I'm can't figure out a way of displaying a message if a specific word is inputed into an input box. I'm basically trying to get javascript to display a message if a date, such as '01/07/2013', is inputed into the input box.
Here is my html
<p>Arrival Date</p> <input type="text" id="datepicker" id="food" name="arrival_date" >
I'm using a query data picker to select the date.
You can insert code in attribute onchange
onchange="if(this.value == 'someValue') alert('...');"
Or create new function
function change(element){
if(element.value == 'someValue'){
alert('...');
}
}
And add attribute
onchange="change(this);"
Or add event
var el = document.getElementById('input-id');
el.onchange = function(){
change(el); // if 'el' doesn't work, use 'this' instead
}
I'm not sure if it works, but it should :)
Use .val() to get the value of the input and compare it with a string
var str = $('#datapicker').val(), // jQuery
// str = document.getDocumentByI('datapicker').value ( vanilla js)
strToCompare = '01/07/2013';
if( str === strToCompare) {
// do something
}
And encase this in either change or any keyup event to invoke it..
$('#datepicker').change(function() {
// code goes here
});
Update
Try the code below.
$(function () {
var $datepicker = $('#datepicker');
$datepicker.datepicker();
$datepicker.on('change', function () {
var str = $datepicker.val(),
strToCompare = '07/19/2013';
if (str === strToCompare) {
console.log('Strings match')
}
else {
console.log('boom !!')
}
});
});
Check Fiddle
Your input has 2 ids. You need to remove id="food". Then the following should work with IE >= 9:
document.getElementById('datepicker').addEventListener(
'input',
function(event) {
if (event.target.value.match(/^\d+\/\d+\/\d+$/))
console.log("Hello");
}, false);

How to Listen for Upload Finished with jQuery in WordPress Thickbox Upload Window?

I'm injecting some jQuery to make the Alt Text field required in WordPress upload thick box.
It intercepts the Insert into Post button click and checks if the field has been filled or not.
It works ok for the Gallery and Media Library tabs, but the From Computer tab needs a needs a "listener" when an upload finishes to alter the behavior of the Insert into Post button.
I was trying with setInterval, but don't know how to kill or recreate it, but maybe someone is aware if a listener exists, or even how to make this code work because I suspect my logic here is fuzzy...
Here's the code, commented.
add_action('admin_head-media-upload-popup','so_11149675_required_alt_text');
function so_11149675_required_alt_text()
{
// Detect current tab ("From Computer" == "type")
$tab = isset($_GET['tab']) ? $_GET['tab'] : "type";
// ( 'From Computer' or ( 'Gallery' and 'Library' ) )
$jquery = ('type' == $tab) ? 'var refreshUpload = setInterval(function(){$(".savesend input").each(checkAltTextPermanent);},500);' : '$(".savesend input").each(checkAltTextOnce);';
echo <<<HTML
<script language="javascript" type="text/javascript">
// var refreshUpload; /* testing */
// Function called by From Computer tab
// should run only once -> when the upload table and fields are created
function checkAltTextPermanent() {
// Create the required asterisk symbol
// setInterval creates a loop here
jQuery('.image_alt th label').each(function(i,e) {
jQuery('<span class="alignright"><abbr title="required" class="required">*</abbr></span>').prependTo(this);
});
// Alter button behavior
// Another loop in the alert box
jQuery(this).click(function(e) {
// clearInterval(refreshUpload);
var value = jQuery(this).parent().parent().parent().find('.image_alt input').val();
if('' != value)
return true;
alert ('Please fill the Alt text');
return false;
});
}
// Function called by Gallery and Library tabs
function checkAltTextOnce() {
jQuery(this).click(function(e) {
var value = jQuery(this).parent().parent().parent().find('.image_alt input').val();
if('' != value)
return true;
alert ('Please fill the Alt text');
return false;
});
}
jQuery(document).ready(function($) {
// Defined in PHP, calls checkAltTextOnce or checkAltTextPermanent
{$jquery}
// Used in Gallery and Libray tabs
$('.image_alt th label').each(function(i,e) {
$('<span class="alignright"><abbr title="required" class="required">*</abbr></span>').prependTo(this);
});
});
</script>
HTML;
}
Try this:
jQuery(".savesend input").live("click", validateAltText);
function validateAltText() {
var value = $(".image_alt input").val();
if (value)
return true;
alert('Please fill the Alt text');
return false;
}

How to disable a Javascript Function when a different one is Enabled?

I have this function:
$(document).ready(function(){
function Fos(buttonSel, inputSel, someValue, cssProperty) {
$(buttonSel).click(function(){
var value = $(inputSel).attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, someValue, this.id)
var css_obj={};
css_obj[cssProperty]=value;
$(this).css(css_obj);
});
});
}
Here are three places where function is written:
Fos('#border_button', '#border-radius', 2, '-webkit-border-radius');
Fos('#background_color_button', '#background-color', 1, 'background-color');
Fos('#opacity_button', '#opacity', 3, 'opacity');
<input type="text" id="border-radius" value="20px">
<div id="border_button">BORDER RADIUS</div>
<input type="text" id="background-color" value="red">
<div id="background_color_button">Background</div>
<input type="text" id="opacity" value=".5">
<div id="opacity_button">Opacity</div>
<div id="2" class="defaultclass editable" style="<?php getStyle('2') ?>">
something
</div>
When you click the DIV with the ID= "border_button", or "background_color_button", or "opacity_button"
it waits for you to click any DIV with class="editable", ...$("div.editable").click(function (e) {... it executes the function with those parameters.
I just need a fix that will only allow ONE function with the parameters to be enabled at one time.
Currently, when you click on all three divs with ID = "border_button", or "background_color_button", or "opacity_button" AND THEN on a div with class="editable", it executes the function with ALL THREE sets of parameters.
This is bad. I can't figure it out.
You can't "disable" a function, but you can set a variable that will force it to exit right away:
var stopMe = true
function myFunction() {
if(stopMe) {
return;
}
...
}
You seem to be binding and rebinding the same functions over and over, which is probably why you have that e.stopEventPropagation in there. Try assigning the events once and then managing the current state (which button is active) and going from there:
var $currentInput = null;
$("#border_button,#background_color_button,#opacity_button").click(function() {
if ($currentInput == null) {
$currentInput = $(this).prev();
}
});
$("div.editable").click(function(e) {
if ($currentInput == null)
return;
$(this).css(GetCssProperties());
showUser($currentInput.val(), /* where does someValue come from? */, this.id)
$currentInput = null;
});
function GetCssProperties() {
if ($currentInput == null) return null;
var value = $currentInput.val();
if ($currentInput.attr("id") == "border-radius") return {
"-webkit-border-radius": value
}
if ($currentInput.attr("id") == "background-color") return {
"background-color": value
}
if ($currentInput.attr("id") == "opacity") return {
"opacity": value
}
}
working example here: http://jsfiddle.net/HUJ5A/
Run the function for tag with a specific class. And a the end of the function remove this class from the tag.
jQuery(".myclass").click(function(){
/* do something */
jQuery(this).removeClass('myclass');
});
Can't tell everything from your question. But this part $("div.editable").click(function (e) { will bind multiple click events to div.editable each time the user clicks Foo arugments[0] or buttonSel.
This could be a pssible solution:
Have a global variable (or HTML hidden input) say, lastDivClicked, to store the id of the recently clicked div
Update lastDivClicked everytime one of those three divs are clicked upon
Change your function to this:
function Fos(inputSel, someValue, cssProperty) {
var buttonSel = $('#lastDivClicked').val();
$(buttonSel).click(function(){ ... }
}

Categories