How to get value from selected input field (not using id) - javascript

I try to do simple code for guessing notes by ear. I have tabs with several empty input fields and you need to put right numbers in these fields according to certain melody (for guitar fretboard) . One button shows first note, another button checks whether you put right or wrong number and depend on it approves or erase your number.
I know how to check every input field using its id's but can i do it such way that when i push 2nd button it get value from selected input and compare it to its placeholder or value attribute?
It is my codepen
https://codepen.io/fukenist/pen/BxJRwW
Script part
function showfirst() {
document.getElementById("fst").value = "12"
}
function show1other() {
var snote = document.getElementById("scnd").value;
if (snote == 9 ){
document.getElementById("scnd").value = "9";
}
else {
document.getElementById("scnd").value = "";
}
}

You can use document.querySelectorAll() to get all your inputs and loop over them.
Sample:
// Get all inputs as an array (actually NodeList, to be precise; but it behaves similar to an array for this use case)
var inputs = document.querySelectorAll('input');
// Function to reveal the first input's value
function showFirst(){
inputs[0].value = inputs[0].dataset.v;
}
// Function to check all values and clear input if wrong
function checkAll(){
inputs.forEach(function(input){
if(input.dataset.v !== input.value){
// Wrong answer, clear input
input.value = '';
}
});
}
<input data-v="12" size="2" value=""/>
<input data-v="9" size="2" value=""/>
<input data-v="8" size="2" value=""/>
<br/>
<button onclick="showFirst()">Show First</button>
<button onclick="checkAll()">Check All</button>
Notes:
I have used data-v to store the correct answer instead of placeholder as that attribute has a semantically different meaning
It may be out of turn but my two cents: Writing out entire songs like this by hand may become tedious. Consider using a JSON string or something similar to map out the tabs and use a templating framework to align them.. Some things you may need to look out for while designing something like this : Alignment of notes (successive notes, simultaneous notes), timing of the song, special moves like slide, hammer on etc.
It may be a better idea to make the Guitar Strings be a background element (either as a background-image or as absolutely positioned overlapping divs) (so You don't have to worry about the lines going out of alignment)
Reference:
HTMLElement.dataset
document.querySelectorAll

Related

AngularJS - Replace values in array based on input text box changes

I have a simple text box -
<input type="text" class="form-control" id="inputID" name="ItemId" ng-model="inputItemId" ng-required="true" ng-blur="addValueToArray(inputItemId)"/>
The number of input boxes increase and decrease based on the user's choice (I have a simple add/subtract functionality that replicates the text boxes or removes them), but they ultimately are all stored in an array -
$scope.itemIDs = [];
$scope.addValueToArray = function(inputItemId)
{
$scope.validID = $filter('uppercase')(inputItemId);
$scope.itemIDs.push($scope.validID);
}
My $scope.itemIDs array holds all the IDs the user has entered in the various text boxes.
Say the values in this array right now are - ABC,ABD,ABE,ABZ for four different items.
What I wish to achieve now is, if a user decides to remove the second value ABD and replace it with ABW in the text box, based on how my function works, it ends up adding it after the last element of the array and looks like - ABC,ABD,ABE,ABZ, ABW.
Is there a way in angular where I could replace the entered value of the second value with the new one in the array instead of adding it in the end? Am I missing out on something?
Try something like this,
$scope.itemIDs = [];
$scope.addValueToArray = function(oldValue,newValue){
$scope.itemIDs[$scope.itemIDs.indexOf(oldValue)] = newValue;
}

How to pass a user entered form value from html to javascript?

It is possible to pass a value from javascript to html by writing it to a tag. However, if I would wish to pass a user defined value (etc, entered by the person viewing the webpage) to java script so I can do things with it, what would be the most easiest way possible?
At the moment, I have something like this:
<div class="entry foreground-color">
<form>
<input type="text" name="commands" size="60"/>
</form>
</div>
How can I make the value from the form be passed to my javascript?
Or, am I going in a totally wrong direction? If so, what would be the correct way to get user input, and pass it on to javascript?
EDIT: Apologies for my misuse of terminology. I am making a text based adventure game, and I want the user to be able to type in a response, press enter, and have the response be sent to javascript, so I can use javascript to evaluate the response (etc "go south", "go north"), and write back to the element with the new situation (etc "as you went south, you found a troll").
You can just stop the form from submitting and get the value:
HTML:
<div class="entry foreground-color">
<form onsubmit="return getValue('commands')">
<input type="text" name="commands" size="60" id="commands"/>
</form>
</div>
JavaScript:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
return false;
}
Fiddle: Fiddle
If you want to clear the box afterwards, use:
document.getElementById(id).value = '';
Like so:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
document.getElementById(id).value = '';
return false;
}
The input value is already available for Javascript via DOM API:
document.getElementsByName( "commands" )[0].value
You can get the value of your input control using:
document.getElementsByName("commands")[0].value;
Since getElementsByName() method returns an Array of elements with specified name, you will need to take the first element assuming that there is only one elements with name attribute commands.
Instead of that, for simplicity and uniqueness, i suggest you use the famous way to achieve that using id attribute and getElementById() method.
<input type="text" name="commands" size="60" id="commands"/>
var input = document.getElementById("commands").value;
or
document.getElementsByName( "commands" )[0].value
now do anything with this
To get the value of an HTML element, first, you need to get the desired element (you can use theses methods):
getElementById
getElementsByTagName
getElementsByClassName
querySelector (moderns browsers)
querySelectorAll (moderns browsers)
Theses methods depending on document (documentation).
So in your case you can try something like this:
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
But you need to set a "catcher" on the form default action.
So:
<form>
Become:
<form onsubmit="return getValue()">
And you set the javascript code above in the getValue function:
function getValue() {
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
return false; // prevent default form action
};
You are in the right path :)
For example you can do something like this (see http://jsfiddle.net/ahLch/):
HTML:
<h1 id="commandsExample"></h1>
<div class="entry foreground-color">
<form>
<input type="text" id="commands" size="60"/>
</form>
</div>
JavaScript:
var input = document.getElementById('commands');
var example = document.getElementById('commandsExample');
input.addEventListener('change', function () {
example.innerHTML= input.value;
});
A couple of things to note:
If you are new to JavaScript, and you wish to make your code cross browser (especially if you want to target old versions of IE), take a look to jQuery.
If you wish to learn how to use plain DOM APIs provided by the browser without the jQuery layer, take a look to: http://youmightnotneedjquery.com/ (it's very useful once that you learned jQuery basics).
There are a couple of ways to get the value:
Intercepting from submmit event: I don't recommend it, you have to take care of avoiding the default submit behavior, and you have to create a form around your input field. That was necessary in old browsers, but today is not.
change event: it's fired when the input value has changed and the input looses the focus (is the usual event used for form validation).
keydown and keyup: they give you more control, by capturing each keystroke, but it's lower level than the change event. For a complete reference see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
Use "id" instead of "name". Name is only necessary when you want to submit the value, in new browsers you can leave just input tag without a form.
Getting the value of the input tag is quite easy with jQuery.
(I take it you need this anyway to actually send the message via AJAX to a server..?)
$("#idofinput").val(); will copy the value, $("#idofinput").val(''); will empty it.
You probably want to do this without actually submitting a form.
Recreating one in javascript isn't to hard.
For the submit on enter you can use something like this:
function checkEnter(e)
{
var keynum;
if(window.event) // IE8 and earlier
{
keynum = e.keyCode;
}
else if(e.which) // IE9/Firefox/Chrome/Opera/Safari
{
keynum = e.which;
}
if(keynum==13)
{
sendMessage();
}
}

Repeat a div with javascript?

I am not sure how to phrase what I'm asking (or I would probably be able to find it). What is it called when you have an indefinite number of items to add to a webpage form for submission to a db? For example, if you have a resume web site, and you want to add experience. You may have a slot for one job, and an "Add more experience" to that. What is that called? How do you implement that (js, html, css)?
EDIT:
Thanks for the comments. This is called: dynamically add form elements.
this is a basic idea ,,
http://jsfiddle.net/3mebW/
var noOfFields = 2;
$('#addNew').on('click', function(e) {
e.preventDefault();
var newField = '<br><label for="experience'+noOfFields+'">experience'+noOfFields+'</label>';
newField += '<input type="text" name="experience'+noOfFields+'"class="field"/>';
$('.field:last').after(newField);
//adding a hidden input inside the form to know the number of inserted fields
//make sure that the input is not already here
//then adding it to handle the number of inputs later
if($('#noOfFields').length === 0){
$('#Frm').append('<input type="hidden" value="2" id="noOfFields"/>');
}else{
$('#noOfFields').attr('value',noOfFields);
}
noOfFields++;
});
you can also detect the number of fields using a class or any other method
You can do this using the jQuery function .clone().
Here's the jQuery doc about it : http://api.jquery.com/clone/
You can copy your Experience input field, and set its properties (ID, name, etc) before appending it where you want.
lots of ways to do this, here is is one
http://jsfiddle.net/uuKM8/
$('#myBtn').click(function(){
$( "#myInput" ).clone().appendTo('body');
});

Show Input Box on Check

You can see in the paper form attached what I need to convert into a web form. I want it to show the check boxes and disable the input fields unless the user checks the box next to it. I've seen ways of doing this with one or two elements, but I want to do it with about 20-30 check/input pairs, and don't want to repeat the same code that many times. I'm just not experienced enough to figure this out on my own. Anyone know anywhere that explains how to do this? Thanks!
P.S. Eventually this data is all going to be sent through an email with PHP.
I don't think this is a good idea at all.
Think of the users. First they have to click to enter a value. So they always need to change their hand from mouse to keyboard. This is not very usable.
Why not just give the text-fields? When sending with email you could just leave out the empty values.
in your HTML :
//this will be the structure of each checkbox and input element.
<input type="checkbox" value="Public Relations" name="skills" /><input type="text" class="hidden"/> Public Relations <br/>
in your CSS:
.hidden{
display:none;
}
.shown{
display:block;
}
in your jQuery:
$('input[type=checkbox]').on('click', function () {
// our variable is defined as, "this.checked" - our value to test, first param "shown" returns if true, second param "hidden" returns if false
var inputDisplay = this.checked ? 'shown' : 'hidden';
//from here, we just need to find our next input in the DOM.
// it will always be the next element based on our HTML structure
//change the 'display' by using our inputDisplay variable as defined above
$(this).next('input').attr('class', inputDisplay );
});
Have fun.
Since your stated goal is to reduce typing repetitive code, the real answer to this thread is to get an IDE and the zen-coding plug in:
http://coding.smashingmagazine.com/2009/11/21/zen-coding-a-new-way-to-write-html-code/
http://vimeo.com/7405114

Removing an <option> from a <select> tag according to previously selected <option> tag? (POLL Example)for

I have 50 rows of data and i want users to give them points by 1 to 50. I put dropdown boxes near them with options 1/50. But all i want is when a user selects 15(for example) for a row, 15 will be deleted from all other select tags of other rows. I am not as good as you in JavaScript. How can i accomplish this?
Hi casablanca i couldnt make he script you sent work. I need it to work on just one select tag so i give select tag an ID and an ID for the form too. I edit the scripts getElementsByTagName with getElementsByTagID (select tag's ID) to effect only one select tag. But the function doesnt triggered?
This might not be a very good idea, because it is very difficult for the user to modify choices -- for example, if I want to give 15 to a different option, I need to change the old one to something else and then change the new one to 15. Also, once all points have been assigned, it's impossible to make any changes because all options are gone.
A better idea would be to let the user do whatever he/she wants and then validate the form in the end. You could do that like this:
function validate() {
var used = []; // This array stores already used options
var rows = document.getElementById('myForm').getElementsByTagName('select');
for (var i = 0; i < rows.length; i++) {
var points = rows[i].value;
if (used[points]) {
// This value was already used
alert('Please choose a different value.');
rows[i].focus();
return false;
} else {
// This value was not used before; mark it as used now
used[points] = true;
}
}
return true;
}
And call this function in the onsubmit handler of your form:
<form id="myForm" onsubmit="return validate();">
EDIT1: id -> class
give each option the class of the number it is
<option class="15">15</option>
<option class="16">16</option>
etc.
Then jquery can remove() an item by class
$('.15').remove();
obviously have to do an on change and get the value just set. "remove()" is nice in this instance because I believe it will yank every instance of that class.
EDIT3: upon further consideration the above method would be further complicated by the need to not remove the "selected" option. Not going to figure out the exact method but I think changing the class from "15" to "selected15" with a $(this).append() or something of the sort before calling the remove would get the job done fairly safely.
EDIT2:
As noted by casblanca below this is not an ideal user interface at all for this type of input. You may want to look into this: http://www.utdallas.edu/~jrb048000/ListReorder/
Allows user to drag and drop items in a list to reorder them. Much more natural.

Categories