Function to get input and assigns it to variable - javascript

I'm trying to make something using javascript/jquery that is similar to java.
The way to get input in java:
String x = JOptionPane.showInputDialog("Enter a value: ");
.showInputDialog shows GUI and submits a value after "Submit" is clicked.
This is what I've tried: https://jsfiddle.net/1t5pxhj5/2/

This behavior is not possible with Javascript.
You should use events and callbacks to retrieve the specified value.
Your Java code:
String x = JOptionPane.showInputDialog("Enter a value :");
Your Javascript code:
function showInput(message, callback) {
// display dialog
// ...
callback($("input").val()); // this should be returned to getInput after Submit is clicked
});
showInput("Enter a value:", function(x) {
// do something now
});

<input type="text" name="txt" id="txt"/>
<input type="button" onclick="gettext('txt');"/>
to retrieve data use code below
function gettext(id) {
var entereddata = document.getElementById(id);
var value = entereddata.value;
}
Hope my code works. Keep coding

Supposing you have
<input type="text" class="my-input">
<button>click me!</button>
you can retrieve input value in jQuery/Javascript with this instruction;
$(".my-input").val();
if you want to bind the data retrieval to the "click me!" button there is the complete code:
$(".click-me").click(function() {
alert($(".my-input").val());
});

Related

Not able to reset input field in laravel

I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.
<input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
JS for reset button:
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = "";
};
Reset Button:
<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
Use type="reset" for your button:
<button type="reset">Cancel</button>
try using reset():
document.getElementById("app_number").reset();
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.
$('#app_number').on('change', function () {
// enter code here
});
Please try to use in js like:
$(document).on('click', '#YourOnclickButtonID', function(){
var $alertas = $('#YourFormID');
$alertas.validate().resetForm();
});
So answering my own question, any feedback would be appreciated but this is working.
It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.
So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.
I added onkeyup event ion to the input field
<input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>
and JS to store and retrieve input
document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input
function saveValue(e) {
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return ""; // You can change this to your defualt value.
}
return localStorage.getItem(v);
}
and then reset the form as usual
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};
Your reset button :
<button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>
In js:
function myFunction(){
document.getElementById("app_number").value = "";
}

Use changed values in other page

I have a textfield:
Voornaam: <h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
I can set a value of this using this function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
Now in my other page, I want to use the value. I know I can for example pass a value from one page to another like this:
<a href='convert.php?var=data'>converteren.</a>
And then for example show it by doing this in the other page:
echo $_GET['var'];
But I cant really seem to figure out how to use the value which I've set using my textfield.
So my goal for now is to display the value I've set using my textfield in the other page using the method I just described.
Basically all I want to happen is for my textfield to change the value inside here aswell:
<a href='convert.php?var=data'>converteren.</a>
So where data is the value, I want it to become what I've put in the textfield.
Could anybody provide me with an example?
I've altered a bit your javascript code to make the link as you want.
To explain the answer, i've added document.getElementById("myLink").href="convert.php?var=" + myNewTitle ; which updates your a href while your function runs and is not empty.
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
document.getElementById("myLink").href="convert.php?var=" + myNewTitle ;
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
<a id="myLink" href='#'>converteren.</a>
Wrap your inputs inside a form element.
In the action attribute, specify the destination url.
In the method attribute, choose between GET and POST.
For example:
<form method="GET" action="convert.php">
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/>
</form>
Clicking the submit button will call "convert.php?myTextField1={value}".

Modify the value of each textfield based on original value using jQuery

Is it possible to modify the value of each textfield present in a webpage, based on the original value, using jQuery or JavaScript?
For example, suppose I have 50 textfields in a page. I want to remove whitespace from the beginning and end of each textfield’s value. I don’t find it to be a good idea to call the function for every textfield individually. How can I do it without calling a function for each textfield?
Can just use val() with a callback argument. It will loop over all elements for you:
$('input[type=text]').val(function( index, originalValue){
return $.trim(originalValue);
});
val() API docs
You can execute this code:
$('input[type=text]').each(function (i, e) {
var $this = $(e);
$this.val($this.val().trim());
});
Get all the inputs from the page using jquery then run a loop, and for each element trim the value
<body>
<input type="text" value=" abc " >
<input type="text" value=" def " >
<input type="button" id="remove" value="Remove">
<script type="text/javascript">
$(document).ready(function(){
$('#remove').click(function(){
var inputs = $('input[type=text]');
$.each(inputs, function(index,input){
$(input).val($(input).val().trim())
});
});
});
</script>
</body>

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

Categories

Resources