return string in javascript - javascript

I want to get apiUrl depending on a user's input
<form name="test">
<input type="text" name="Edit">
<input type="button" value="Test" onClick="gettext()">
<input type="text" name="Edit2" readonly style="border:1px solid white">
</form>
Then i have a script which does not work, to form a url based on that
<script>
function gettext(Edit, Edit2) {
document.test.Edit2.value=document.test.Edit.value;};
var apiKey = '07gh4c95ca7e23d41ghggf/';
var userWord = Edit2;
var txtjson = '/json';
var apiUrl = 'http://words.bighugelabs.com/api/2/' + apiKey + userWord + txtjson;
</script>
I need var userWord to be a string to insert its value in the apiUrl.
Please help me with that. Thank you

Edit2 is not declared outside the gettext function. Try this:
function gettext(Edit, Edit2) {
document.test.Edit2.value = document.test.Edit.value;
return document.test.Edit2.value;
}
var userWord = gettext(<param1>, <param2>);

Related

how to add fields with increased number in name to a form using javascript?

I have a form that looks like this:
<form action="/a1/configurer/1" method="post">
<label>Fill out a revenue (such as "salary")</label>
<input type="text" name="revenu_0[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_0[amount]">
Add revenus
In this add_field() function I want to add this :
<label>Fill out a revenu</label>
<input type="text" name="revenu_1[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_1[amount]">
And when clicking the button again, name is "revenu_2" and so on (incrementing).
I have tried this:
function add_field() {
i = 1;
var extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
i = i + 1;
document.getElementsByTagName('body')[0].appendChild(extra);
}
That's only a very small part of the solution and obviously, this doesn't increment.
How do I do this?
You are pretty close. The important piece you're missing is to make sure i is declared outside the add_field function scope. Then, each time you call the function, the previous value of i will be persisted in the outer scope. See below for a working example.
let i = 1;
function add_field() {
const extra = document.createElement("input");
extra.setAttribute("type","text");
extra.setAttribute("name","revenu_" + i + "[categorie]" );
extra.setAttribute("placeholder", "Field " + i);
document.getElementsByTagName('form')[0].appendChild(extra);
i = i + 1;
}
<button onclick="add_field()">Add field</button>
<form></form>
Solution #1
var i = 1;
btn.onclick = () => {
var label = document.createElement('label'),
input = document.createElement('input'),
br = document.createElement('br');
label.innerHTML = 'Label text ';
input.type = 'text';
input.name = 'revenu_' + i + '[category]';
input.placeholder = 'Field #' + i;
myForm.appendChild(label);
myForm.appendChild(input);
myForm.appendChild(br);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Solution #2
var i = 1;
btn.onclick = () => {
var add = `
<label>Fill out a revenu</label>
<input type="text" name="revenu_${i}[category]">
<label>And the monthly amount</label>
<input type="text" name="revenu_${i}[amount]">
<br>
`;
myForm.insertAdjacentHTML('beforeend', add);
console.log(add);
i++;
}
<button type="button" id="btn">Add input field</button>
<form id="myForm"></form>
Notice that in both cases:
button must have id="btn";
form must have id="myForm".
Obviously, if you change those ids in the HTML code, you need to change them in the JS code as well.

Why is this simple Javascript refactor not working?

A simple question about a form submit in HTML.
Why does this work:
var inputStuff = document.getElementById("inputBox");
var output = document.getElementById("outputBox");
function useMethod(element) {
output.innerText = inputStuff.value;
return false;
}
But this doesn't:
var inputStuff = document.getElementById("inputBox");
var output = document.getElementById("outputBox");
function useMethod(element) {
var out = output.innerText;
var into = inputStuff.value;
out = into;
return false;
}
Here's the HTML:
<h1>Put your input in here</h1>
<form onsubmit="return useMethod(this)" action="">
<input type="text" id="inputBox">
<input type="submit" value="Submit">
</form>
<h2>Output:</h2>
<p id="outputBox">Starter text</p>
Many thanks in advance for any help,
R
out = into; will simply assign the value of into (string) to out (string), whereas output.innerText = inputStuff.value; will invoke an implicit setter that will change the DOM value as well.

I cannot connect javascript function with html <input> tags and onclick doesn't work

Hi I am working on a website and i stumbbled across an annoying thing. I cannot, for the love of anything, get to work my form to be able to do some maths and insert them into tag.
P.S nothing works for me, even GetElementsById... or other callouts :(
<script type="text/javascript">
function price(this.form){
var amount = form.elements[1].value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = (amount/gold_price) + " M";
window.alert("price_calc");
form.elements[5].value = price_calc;
}
</script>
//this is input that i would like to get a number to work with in the function
<div>
<input type="text" id="amount" value="10" onchange="price(this.form)" onclick="price(this.form)" maxlength="4" required/>
</div>
//this is input I would like to write in in after function is done functioning :)
<input type="text" id="total_price" placeholder="Total:"/>
thanks for any help in advance.
thanks again,...
Declare your price function to receive an input parameter. Actually this.form as parameter is an invalid statement and leads to an error.
Instead pass this (inside your on* property) and select the input value.
// select #total_price
const totalPrice = document.getElementById( 'total_price' );
function price( input ) {
// Convert value to a number
var amount = +input.value;
var gold_price = 0.17;
var price_calc = 0;
price_calc = ( amount / gold_price ) + " M";
totalPrice.value = price_calc;
}
<input type="text" id="amount" value="10" oninput="price( this )" onclick="price( this )" maxlength="4" required/>
<br>
<input type="text" id="total_price" placeholder="Total:" />
This code working:
<input type="text" value="10" oninput="price(this)" maxlength="4" />
<input type="text" id="total_price" placeholder="Total:" />
<script>
function price(el){
var amount = parseInt(el.value);
var gold_price = 0.17;
var price_calc = (amount / gold_price) + " M";
window.alert("Total: " + price_calc);
document.getElementById('total_price').value = "Total: " + price_calc;
}
</script>

.test() method in javascript is not working properly

In this code, the variable value of "ans" is always false whether I have entered value according to pattern or not. I cannot understand the reason.
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
Try this
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
<script>
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
</script>
You should move all your code into a defined function validate()
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
You used function named validate in the submit button event, but did not define it. After defining the validate function, everything works fine.
function validate() {
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>

Generating JSON String from Form

I am new to JSON and trying hard to understand it's working.
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID">
<button type="submit" class="btn btn-success" >Submit Data</button>
</form>
JSON String to be generated as:
{"latency":1.6,"throughput":6.01,"outUID":{"V_ID":"40"},"inUID":{"V_ID":"16"}}
Here's the form and JSON String to be generated
Could some one guide me how do I create that nested JSON object?
Since it looks like you want the values of outUID and inUID to be nested for some reason you'll need to build the object manually. Here's a simple example:
var $latency = $('#latency'),
$throughput = $('#throughput'),
$outUID = $('#outUID'),
$inUID = $('#inUID');
var myJSONObject = {
latency:$latency.val(),
throughput:$throughput.val(),
outUID:{
V_ID:$outUID.val()
},
inUID:{
V_ID:$inUID.val()
}
};
var stringJSON = JSON.stringify(myJSONObject);
Pure javascript example
var els=document.getElemtById('edge').getElementsByTagName('input');
or
var els=document.querySelectorAll('input[class=input-"xlarge"]');
to get the elements
then
var array=[]
for(var a=0,b;b=els[a]; ++a){
array[a]=b.value
}
array is the json object
JSON.styringify(array)
is the json string
tip: if you plan to use this with ajax
there is a new way called FormData();
so:
var fd=FormData(document.getElemtById('edge'));
contains the whole form , including files
This code allow you to add more fields if required to do so without hard coding the field attributes
http://jsfiddle.net/6vQY9/
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID" data-prop="V_ID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID" data-prop="V_ID">
<button type="submit" class="btn btn-success">Submit Data</button>
</form> <pre></pre>
JS
function submit() {
var JSONString = "";
jQuery('#edge input').each(function () {
var that = jQuery(this);
var val = that.val();
var partJSON = "";
var quote = "\"";
if (that.data('prop')) {
partJSON = "{ " + quote +that.data('prop') + quote+ " : " + quote + val + quote + " }";
} else {
partJSON = val;
}
var comma = that.next('input').length > 0 ? "," : "";
partJSON = quote + that.prop('id') + quote + ":" + partJSON + comma;
JSONString += partJSON
});
JSONString = "{ " + JSONString + " }";
jQuery('pre').text(JSONString);
}

Categories

Resources