Converting an integer into a string array and outputting it - javascript

I want to change my input an Integer into a String array. I used javascript to write such a function but unfortunately it doesnt work. I tried everything i know but i have no clue what i did wrong. Would appreciate some help/explanations etc. Here is the code.
<script type="text/javascript">
function convert() {
var umge = document.getElementbyId('eingabe').value;
if(umge == 0005010) {
var aus = {"Maria", "Nord", "1a", "VS Langenzersdorf"};
var myJSON = JSON.stringify(aus);
document.getElementById('output').innerHTML = myJSON;
document.getElementById('input').innerHTML = "";
}
}
</script>
</head>
<body bgcolor="orange">
<form action="" method="post">
<input type="text" name="input" id="input" value="0005010">
<input type="submit" value="Umwandeln" onclick="convert();">
<p name="output" id="output"> Kein Wert</p>
</form>
</body>
</html>

Other than the problems mentioned in the comments, your declaration of aus is wrong: an object should be {k1:"v2"} and an array should be ["v1","v2"].
Also, your input box is type text, so its value is a string, not a number, so you need to compare it to a string. I cleaned up your code into something runnable here : https://plnkr.co/edit/Sny3LuBDGh0ZKHY0lSWx?p=preview
Basically you should either do this :
var umge = document.getElementById('input').value;
if(umge == "0005010") { .... }
Or something like this :
var umge = parseInt(document.getElementById('input').value);
if(umge == 5010) { .... } // note - no leading 0s!

Related

How can I convert the value written in HTML input to the string variable?

var imie = document.getElementById("imim");
function wypisz_imie() {
document.getElementById("powitanie").innerHTML = "Czesc!" + imie;
}
<!DOCTYPE>
<html>
<head>
<title>My city v1.0</title>
</head>
<body>
<script type="text/javascript" src="skrypt.js"></script>
<h2>Wpisz jak masz na imie</h2>
<input type="text" id="imim" value="" />
<input type="submit" id="potwim" value="potwierdz" onclick="wypisz_imie()" />
<h1 id="powitanie"></h1>
</body>
</html>
Sorry for my English cause i'm from Poland and i'm new user. I'll be thankfull for answers!
You can use document.getElementById("imim").value to get the text in the text field. It's up to you what to do from there!
imie will return the input element so you should use value property like this:
var imie = document.getElementById("imim");
function wypisz_imie()
{
document.getElementById("powitanie").innerHTML = "Czesc!" + imie.value;
}
imie.value will return the value of input.
check w3s.
but every time the value will return "", to solve this problem you should access input every time call function to return input with new value like this:
function wypisz_imie()
{
var imie = document.getElementById("imim");
document.getElementById("powitanie").innerHTML = "Czesc!" + imie.value;
}

Javascript replace function "is not a function"

I have an issue with the following code. I want to replace a string by another one, and generate an img code. However, I got an error message: str.replace is not a function. Any idea why?
<input type="text" id="text">
<input type="button" value="See Code" onclick="myFunction();">
<input type="text" id="code" name="code">
<script>
function myFunction() {
var str = parseInt(document.getElementById("text").value);
var res = str.replace("ftpadress", "htmladress");
var code = str.concat("<img src='",res,"' width='100%'>");
document.getElementById("code").value = code;
}
</script>
As #mrlew pointed out,
str is result of parseInt and therefore, it's a number. replace() is a string method, so it will not work on a number.
If I understood correctly, you would like to replace a string, retrieve a code and then generate an image tag with the new string and code.
I'd go with...
<input type="text" id="text" />
<input type="button" value="See Code" onclick="myFunction();">
<input type="text" id="code" name="code">
<script>
function myFunction() {
//changed
var str = document.getElementById("text").value; //get text
var res = str.replace("ftpadress", "htmladress"); //replace
var code = parseInt(str).toString(); //get code and cast it back to a string
document.getElementById("code").value = code; //insert code
var withTag = code.concat("<img src='", res, "' width='100%'>"); //generate tag
}
</script>
parseInt returns an integer not a string so you can not use str.replace() , you need to cast it first
just add str = str.toString(); before using the replace function
Just remove the casting (parseInt function) and everything should work fine.
<input type="text" id="text">
<input type="button" value="See Code" onclick="myFunction();">
<input type="text" id="code" name="code">
<script>
function myFunction() {
//changed
var str = document.getElementById("text").value;
console.log(str);
var res = str.replace("ftpadress", "htmladress");
var code = str.concat("<img src='",res,"' width='100%'>");
document.getElementById("code").value = code;
}
</script>

Send only filled fields via GET

Look at simple form below:
<form method="GET" action="index.php">
<input type="text" name="price_min" >Min
<input type="text" name="price_max" >Max
</form>
When I send form with filled only one field, in my url I get empty values for not filled keys
(ex. index.php?price_min=).
Question:
How to remove empty keys from url?
You can parse serialized string and remove blank values. Then you can use post to necessary api using jQuery.
Sample
JSFiddle
$("#btn").on("click", function() {
var formjson = $("#frmTest").serialize();
var result = formjson.split("&").filter(function(val) {
return val.split("=")[1].length > 0;
}).join("&")
console.log("Serialized String:", formjson);
console.log("Processed String:", result);
// $.get('action.php', formjson, function(response){ ... })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="frmTest">
<input type="text" name="price_min">Min
<input type="text" name="price_max">Max
</form>
<button id="btn">Test Serialize</button>
Use jQuery to send the fields like this
$('your_form').submit(function() {
var min_price = $("#min_price").val();
var max_price = $("#max_price").val();
var string = "";
if(min_price.length > 0){
string += "min_price="+min_price
}
if(max_price.length > 0){
string += "&max_price="+max_price
}
window.location.href = 'index.php?'+string;
});
Hope it helps!

PHP Validation using AJAX / JSON

My validation is in my php script encoded in json, I'm not sure how to implement it in my main JavaScript function.
I'm using regular expressions to in my php script to validate the form criteria, I need to pass this to the JavaScript file and return a success massage for for each form id.
this is what I have so far.
$(document).ready(function()
{
$("#submit").click(function()
{
// Clear any success or error messages
$("#success").html("");
$("#errors").empty();
//make an AJAX call here, and set error or success accordingly
$.post('backend.php',{act:'validate'},
function(getData)
{
//unsure about this function
}
});
// prevents submit button default behavior
return false;
});
});
<html>
<head>
</head>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name:
<input id="name" type ="text" name="name"></input>
<br><br>
Postal Code:
<input id="postal" type ="text" name="postal"></input>
<br><br>
Phone Number:
<input id="phone" type ="text" name="phone"></input>
<br><br>
Address:
<input id="address" type ="text" name="address"></input>
<br><br>
<input type="submit"></input>
</form>
<div id= "content"></div>
Refresh
<a id="InsertDefault" href="#">Insert Default Data</a>
<br><br>
<p id='msg'></p>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/", $_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/", $_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
Well, this would be better suited for an actual ajax call set up like this (Not Tested)
// Set values
var values = {};
values.act = "validate";
values.name = $('[name="name"]').val();
values.phone = $('[name="phone"]').val();
values.postal= $('[name="postal"]').val();
values.address= $('[name="address"]').val();
$.ajax({
type: 'POST',
url:'backend.php',
data: values,
dataType: 'JSON',
success:
function(result)
{
// Here you can access the json object like this and
// do whatever you like with it
console.log(result.name);
console.log(result.phone);
console.log(result.postal);
console.log(result.address);
}
});
I'm not 100% sure on what you're looking for, but does this work for you? Basically we stringify the object (see my comment about parseJSON) and look for any 0's and submit the form if there aren't any. If there are any 0's we iterate through each key/value pair and push the errors in to an array, then do something with each error, like drop them in the error area. Does that work for you?
var getData = {
name:1,
phone:1,
postal:0,
address:1
}
//if your info isn't looking like this, you may need to look in to $.parseJSON here http://api.jquery.com/jquery.parsejson/
if (JSON.stringify(getData).indexOf('0') == -1) {
alert('all good!');
//$('#PersonForm').submit();
}
else {
var errorArr = [];
$.each(getData, function(k, v) {
if (v == 0) {
errorArr.push('theres a problem with '+k);
}
});
for (var i = 0; i < errorArr.length; i++) {
alert(errorArr[i]);
};
}
Good luck!

Having trouble with input and output in Javascript

I have recently started doing my own project with javascript and I ran into a roadblock. I'm doing a reverse string project where the user inputs a string and the output reverses it. Now my problem is that I can't get the reverse string to show up in the output area.
The Javascript part:
<script>
function pass() {
var input = document.getElementById('inputfield');
var output = document.getElementById('results');
var string = input.value;
var reverse = function (string) {
return string.split('').reverse().join('');
};
output.innerHTML = reverse;
}
</script>
The HTML:
<div id="reverse">
<h1>Type Below:</h1>
<form name="form">
<input type="text" name="inputfield" id="inputfield">
<button onClick="pass();">Submit</button></br>
<input type="text" name="out" placeholder="results" id="results">
</form>
</div>
You need to call the function.
output.value = reverse(input.value);
Luis,
When creating one function that receive an parameter, never forget to send this parameter.
In this case:
output.innerHTML = reverse(yourparameter);
Regards.
you will get reversed string like this:
output.innerHTML = reverse(string);
because
var reverse = function (string) {
return string.split('').reverse().join('');
};
is just a function declaration, the string is only a parameter of the function, but not equal to
var string = input.value;

Categories