Set input value with JavaScript - depending on value of different input - javascript

Hey I got this problem I cannot work out by myself. It's html form which passes data to PHP to send mail.
First, I have dropdown list:
<select id="dropdown" name="dropdown">
<option selected="true" disabled="disabled">Choose</option>
<option id="A" value="one#gmail.com">One</option>
<option id="B" value="two#gmail.com">Two</option>
</select>
This dropdown defines the value of next input:
<input type='text' name="to" id="to" value="e-mail"/>
<script>
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
}
</script>
At last, I need to define third input from the value of second.
<input type='text' name="from" id="from" value="Office manager"/>
But this last code doesn't work for me:
<script>
var name;
if (document.getElementById('to').value == "one#gmail.com" {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
</script>
How do I proceed?
JSFiddle

It does if you put it like this
http://jsfiddle.net/170x1xs9/
document.getElementById('dropdown').onchange = function () {
document.getElementById('to').value = event.target.value
var name;
if (document.getElementById('to').value == "one#gmail.com") {
name = "Martin";
} else {
name = "Tom";
}
document.getElementById("from").value = name;
}

Syntax Error.
if (document.getElementById('to').value == "one#gmail.com" // No ')'
If you use event in your function, you should pass it as an argument.
document.getElementById('dropdown').onchange = function (event /* <-------- HERE */) {
document.getElementById('to').value = event.target.value
}
By not declaring it, you're using window.event, which might work in some browsers, but it's bad practise.

Check out the solution at: http://jsfiddle.net/jam7m5ca/1/
You forgot to pass the parameter event.
document.getElementById('dropdown').onchange = function (event) {
document.getElementById('to').value = event.target.value;
};

Related

Passing user HTML input as javascript function argument

I have this line of javascript:
stave.addClef("treble").addTimeSignature("4/4");
Based on what the user types as input in the HTML document, I'd like to change "4/4" to "3/4," or any other fraction that the user comes up with. What is the easiest way to make this conditional substitution?
Thanks,
Nakul
Here's an option that'll allow a user to toggle number inputs up and down:
<input type="number" id="fraction-1"/>
<input type="number" id="fraction-2"/>
Current Signature:
<div id="current-sig"></div>
Then in your javascript...
// Get the select form element
const FRACT_1 = 'fract-1'
const FRACT_2 = 'fract-2'
const fract1 = document.querySelector(`#${FRACT_1}`)
const fract2 = document.querySelector(`#${FRACT_2}`)
const currentSigDiv = document.querySelector('#current-sig')
let currentSignature = '4/4'
const changeSignatureByFraction = ({target}) => {
if(target.id === FRACT_1)) {
currentSignature = `${target.value}${currentSignature.substring(1)}`
stave.addClef("treble").addTimeSignature(currentSignature)
currentSigDiv.innerHTML = currentSignature
} else {
currentSignature = `${currentSignature.slice(0, -1)}${target.value}`
stave.addClef("treble").addTimeSignature(currentSignature)
currentSigDiv.innerHTML = currentSignature
}
}
// Listen for a change event
fract1.addEventListener('change', changeSignatureByFraction)
fract2.addEventListener('change', changeSignatureByFraction)
currentSigDiv.innerHTML = currentSignature
Create a dropdown list with possible fractions.
Query its value into the variable.
Pass the variable as an argument for addTimeSignature() method.
HTML:
<select id="TimeSignatureSelect">
<option value='1/4'>1/4</option>
<option value='2/4'>2/4</option>
<option value='3/4'>3/4</option>
<option value='4/4'>4/4</option>
</select>
JS:
const timeSig = document.getElementByID('TimeSignatureSelect').value;
stave.addClef("treble").addTimeSignature(timeSig);

How to pass multiple variables from function to multiple jquery attr

This question is related to:
How to pass multiple variables from funtion to jquery attr
So the link above shows multiple solutions on how to pass multiple variables from a regular JavaScript function into multiple jQuery .attr() function values. But the question is, what if you want to send those variables to more than one jQuery functions?
That might sound strange as a statement, that's why I'll include an example.
$(function() {
function definingVars() {
var ValueOne = "Sucess with the value on input 1";
var IdOne = successWithTheId1;
var ClassOne = sucessWithTheClass1;
var ValueTwo = "Sucess with the value on input 2";
var IdTwo = successWithTheId2;
var ClassTwo = sucessWithTheClass2;
return [ValueOne, IdOne, ClassOne, ValueTwo, IdTwo, ClassTwo];
}
$("div:nth-child(1)").attr({
// var df = definingVars(); Incorrect syntax!!!
value: df.ValueOne,
id: df.IdOne,
class: df.ClassOne
})
$("div:nth-child(2)").attr({
// var df = definingVars(); Incorrect syntax!!!
value: df.ValueTwo,
id: df.IdTwo,
class: df.ClassTwo
})
});
input {
width: 20em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="noSucessWithTheId1" class="noSucessWithTheClass1" value="No sucess with the value on input 1">
<input type="text" id="noSucessWithTheId2" class="noSucessWithTheClass2" value="No sucess with the value on input 2">
</div>
Please don't ask about context. This is a dummy example.
$(function() {
function definingVars() {
var Value = "Sucess with the value";
var Id = successWithTheId;
var Class = sucessWithTheClass;
return {
value: Value,
id: Id,
class: Class
};
}
$("input").attr(definingVars())
});
This is one of the answers posted in the question related to this one. It looks beautiful, but it looks impossible to apply this same concept to the situation stated at the beginning of this question.
Not sure if that is what you want to do.
You missed the quotes on some string
I stored the attributes in an array
You should be targetting the input not the div
$(function() {
function definingVars() {
var ValueOne = "Sucess with the value on input 1";
var IdOne = "successWithTheId1";
var ClassOne = "sucessWithTheClass1";
var ValueTwo = "Sucess with the value on input 2";
var IdTwo = "successWithTheId2";
var ClassTwo = "sucessWithTheClass2";
return [{value:ValueOne, id:IdOne, class:ClassOne}, {value:ValueTwo, id:IdTwo, class:ClassTwo}];
}
var df = definingVars();
$("input:nth-child(1)").attr(df[0]);
$("input:nth-child(2)").attr(df[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="noSucessWithTheId1" class="noSucessWithTheClass1" value="No sucess with the value on input 1">
<input type="text" id="noSucessWithTheId2" class="noSucessWithTheClass2" value="No sucess with the value on input 2">
</div>
Changed the selector and returning an object instead of an array to simplify variables.
You can invoke the function and access the object property using the required key.
$(function() {
function definingVars() {
console.log("invoked definingVars");
return {
ValueOne: "Sucess with the value on input 1",
IdOne: "successWithTheId1",
ClassOne: "sucessWithTheClass",
ValueTwo: "Sucess with the value on input 2",
IdTwo: "successWithTheId2",
ClassTwo: "sucessWithTheClass2"
};
};
$($("div>input")[0]).attr({
value: definingVars()["ValueOne"],
id: definingVars()["IdOne"],
class: definingVars()["ClassOne"]
});
$($("div>input")[1]).attr({
value: definingVars()["ValueTwo"],
id: definingVars()["IdTwo"],
class: definingVars()["ClassTwo"]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="noSucessWithTheId1" class="noSucessWithTheClass1" value="No sucess with the value on input 1">
<input type="text" id="noSucessWithTheId2" class="noSucessWithTheClass2" value="No sucess with the value on input 2">
</div>

dynamic name for an input with jQuery

I have an issue with automatic name for input, I'll try to explain what i need to do. i have an id, that I get it from an external function. I need to use this numeric id to create another function like that.
var id = 10; // this is the id (from external function)
var value = "n"+bar.toString(); // (I try to cast the id as string)
$("input[name="+value+"]").on('change', function() { // use the cast value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
When I try to do that I get undefined, but when I change the id like that var id ="10" I get the correct answer, but I have a numeric input. Please help me figure out how to solve this problem.
Did you want something like this? This is based on an assumption that you have checkboxes within a form!
var ids = [10, 20, 30, 11, 12];
$.each(ids, function(index, val) {
var id = val;
var value = "n" + id; // `.toString` is not required!
$("#myForm").find("input[name='"+value+"']").on('change', function() {
if ($(this).is(":checked")) {
alert( $(this).val() );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="checkbox" name="n10" value="10" />
<input type="checkbox" name="n11" value="11" />
<input type="checkbox" name="n12" value="12" />
</form>
use this code no need for id.toString()
var id = getId(); // this is the id (from externel function)
var value = "n" + id;
$("input[name="+value+"]").on('change', function() {
alert($("input[name="+value+"]:checked").val()); //change this selector accordingly
});
function getId() {
return 10;
}
here is the fiddle
https://jsfiddle.net/rrehan/srhjwrz4/
Try below code:
var id = 10; // this is the id (from externel function)
var value = id.toString(); // (i try to cast the id as string)
console.log(value);
$("input[name="+value+"]").on('change', function() { // use the casted value to name my input.
alert($("input[name="+value+"]:checked", "#myForm").val());
});
Demo Link

Get values from submitted form

I have a very simple form:
<form id="toBeTranslatedForm" action="actionpage.php" method="POST" >
<textarea name="userInput" id="toBeTranslatedTextArea"></textarea>
<select id="translationOptions">//dynamically filled</select>
<input type="submit" value="Translate" />
</form>
Using Jquery I am detecting whether the form has been submitted:
function outputTranslated()
{
$('#toBeTranslatedForm').submit(function() {
//do stuff
});
}
How do I get the text typed in the text area and the option selected in the select box from the form above? Ideally I would like to put them into an array.
Javascript only, using FormData:
form.addEventListener("submit", function(e) {
e.preventDefault();
const data = new FormData(form);
for (const [name,value] of data) {
console.log(name, ":", value)
}
})
<form id="form">
<select name="sselectt">
<option value="default" defaultSelected="true">-- Select --</option>
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<label for="inpt">remember</label>
<input id="inpt" name="rrememberr" type="checkbox" />
<button type="submit">submit</button>
</form>
You can get the data form the submit event
function outputTranslated() {
$('#toBeTranslatedForm').submit(function(evt) {
const form = evt.target;
// get the field that you want
const userInputField = form.elements['userInput'];
alert(userInputField.value);
});
}
var theArray = $('#toBeTranslatedForm').serializeArray();
See the .serializeArray docs.
On a pedantic note, that's not "from a submitted form", since you're asking for them before anything is actually submitted.
Here is how you can get value:
function outputTranslated() {
$('#toBeTranslatedForm').submit(function() {
var textareaval = $('#userInput').val();
alert(textareaval);
});
}
You can do the same for selection box by adding this line after the textareaval variable definition in the code above:
var selectval = $('#translationOptions').val();
Then, you can either use serialise, or you can put it into an array manually:
var a = [textareaval,selectval];
I think you'r looking for something like this.
$('#toBeTranslatedForm').submit(function() {
alert($(this).serialize());
return false;
});
Hope it helps
after submission, you can use just get the value by doing the following:
function outputTranslated()
{
$('#toBeTranslatedForm').submit(function() {
var textarea = $('#toBeTranslatedTextArea').val();
var allVals = [];
$('#translationOptions :checked').each(function() {
allVals.push($(this).val());
});
});}

trouble with a currency converter in javascript

Im having trouble with this javascript. here is a n example
window.onload = initPage;
var euro;
var convert;
function initPage()
{
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
}
function calcAnswer()
{
//alert(document.getElementById("conversionType").value);
var value1 = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
//alert(conversionType);
if(var value = document.getElementById("conversionType").value=="polish");
document.getElementById("answer").value=(value1-32)/9*5;
else
document.getElementById("answer").value=value1*9/5+32;
}
here is the html
<h1>Currency Converter</h1>
<form name="convert">
Choose which currency you would like to convert to the Euro:
<select id="conversionType">
<option value="polish">Polish Zloty</option>
<option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>
<hr>
Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
To:
<input id="answer" type="text" name="answer" readonly="readonly"/>
</form>
im using an old temperature converter and havent changed that part part but even that part is not working.
For starters, these two lines are wrong:
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
Change them to:
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
You want to assign a function reference to onclick and onchange, not actually call the function and assign the return value.
Then, fix the if statement in calcAnswer like this:
function calcAnswer()
{
var amount = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
var answerElement = document.getElementById("answer");
//alert(conversionType);
if(conversionType == "polish") {
answerElement.value = (amount-32)/9*5;
} else {
answerElement.value = amount*9/5+32;
}
}
Should be
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
(without the parens)
You just need to reference the function, not execute it.

Categories