change input number by user input not working - javascript

Right now I have an input field:
<input type="number" ng-model="distance"></input>
In the JS I assign the distance to a value:
$scope.distance = 0;
I want this value to change when the user enters in a value and clicks a button. I have the button setup with my controller... But every time the button is clicked, it displays the value as 0.
Function when button is clicked:
//convert button function for when button is clicked
$scope.convert = function(myUnit, myUnit2, distance){
alert(distance);
}
The button:
<button class="button button-block button-balanced" ng-click="convert(myUnit.thisunit, myUnit2.thisunit2, {{distance}})">
Convert
</button>

Change ng-click to this ng-click="convert(myUnit.thisunit, myUnit2.thisunit2, distance)" because you were using {{distance}} interpolation directive inside ng-click directive that will never pass distance value
HTML
<button class="button button-block button-balanced" ng-click="convert(myUnit.thisunit, myUnit2.thisunit2, distance)">
Convert
</button>
Hope this could help you, Thanks.

Depending on the structure of your HTML, (if you have an ngIf above your <input>) the distance model may not be trickling up to your controller.
You should probably nest it for safety, like so:
$scope.formData = {distance: 0};
And then:
<input type="number" ng-model="formData.distance"></input>
Also, your click-handler should just read from the $scope value as well:
$scope.clickHandler = function() {
alert(formData.distance);
}

Related

How can I automatically file an input box and click a search button?

I tried to fill a search input field with some text and hit the search button with this code:
document.getElementsByName('search')[0].value = '1234978';
document.getElementsByClassName('js_search_button')[0].click();
I see my text in the box and the button gets hit. But the data from the input box, was not submited.
Maybe the website has a protection, so that only keytrokes are accepted.
To crosscheck this I tried this code:
var iButton = document.getElementsByClassName('js_search_button')[0];
iButton.addEventListener('click', simulateInput);
function simulateInput() {
var inp = document.getElementsByName("search")[0];
var ev = new Event('input');
inp.value =inp.value + '1234978';
inp.dispatchEvent(ev);
}
Here I get the right result if I manualy click the searchbutton with automaticly filled in the number.
I it possible to automate the click in this scenario, too ?
This is not an answer, because of code sample I posted it as answer.
Are you selecting the right element for clicking? As you can see I click the buttons programmatically.
function clicked(val) {
console.log('button clicked:', val)
}
document.querySelectorAll(".txt")[0].value = 5;
document.querySelectorAll('.btn')[1].click()
document.querySelectorAll('.btn')[2].click()
document.querySelectorAll('.btn')[0].click()
document.getElementsByClassName('btn')[3].click()
<input class='txt' type='text' />
<button class="btn" onclick="clicked(1)">a</button>
<button class="btn" onclick="clicked(2)">b</button>
<button class="btn" onclick="clicked(3)">c</button>
<button class="btn" onclick="clicked(4)">d</button>

Append to value attribute on button click

I am trying to make an input modify each time I click on a button. Kind of like a calculator. The will start at 0. When I click on the button "7" it will change its value to 7, when I click on "4" it will change to 74. Basically like a calculator.
I made this code that does modify the value of the input, however I can't seem to find how I can append more values to that values. Here is my code. Could someone help me?
<input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
<button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->
$('.my-buttons').click(function(){
$(".normal-input").attr("value", $(this).attr('value'));
}); <!-- The actual function. -->
As you can see the function completely replaces the previous value for the new one. I want it to append the values like in a calculator.
I would suggest you to try doing this:
Initialize value to zero
whenever click is called, multiply the current value by 10, and add the button value to it.
and you can remove the step attribute as per the use case.
In this function:
$(".normal-input").attr("value", $(this).attr('value'));
The second parameter is the value to set:
$(this).attr('value')
You need to have this as a combination of the previous value and the new value:
$(".normal-input").attr('value') + '' + $(this).attr('value')
The blank string is to make sure the final result is a string, not the addition of 2 numbers.
If you would like to convert it to a number, you can use parseInt():
const combinedNumber = $(".normal-input").attr('value') + '' + $(this).attr('value')
const intNumber = parseInt(combinedNumber)
The final code could look something like:
<input class="normal-input" type="number" step="0.01"> <!-- Value is NULL-->
<button value="7" class="my-buttons" type="button"> 7 </button> <!--Button to change the value of the input-->
$('.my-buttons').click(function(){
const existingValue = $(".normal-input").attr('value')
const newValue = $(this).attr('value'
const combinedValue = parseInt(existingValue + '' + newValue)
$(".normal-input").attr("value", combinedValue);
}); <!-- The actual function. -->
You just need to concat both the actual value and the value of button which is clicked to get required values .
Demo Code :
$('.my-buttons').click(function() {
var value = $(".normal-input").val()
var clicked_button = $(this).attr('value')
//use val and combined both value
$(".normal-input").val(value + "" + clicked_button);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="normal-input" type="number">
<button value="7" class="my-buttons" type="button"> 7 </button>
<button value="10" class="my-buttons" type="button"> 10 </button>
<button value="6" class="my-buttons" type="button"> 6 </button>

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 = "";
}

Combine 2 Knockout directives with similar logic

I have button "Cancel". On click on which I should show confirmation dialog to ask if user realy want to lost filled in data (in case he made some changes), and just hide form in case he didn't make changes.
I have variable canSave, which helps to detect if there are some changes on form.
cancel - method, which just clear all data and hide form.
This is what I've tried, but this didn't do anything.
<button data-bind="click: canSave ? function(){openConfirmation(!openConfirmation());} : cancel" type="reset" class="btn btn-default">Cancel</button>
Initial Code :
<button data-bind="toggleClick: openConfirmation" type="reset" class="btn btn-default">Cancel</button>
toggleClick is custom directive to change toggle some boolean variable.
<!-- ko if: canSave -->
<confirmation-modal class="delete-confirm-popup" params="showDialog : openConfirmation, bodyHtml: 'Your changes will not be saved.<br/> Do you want to continue?', confirmCallBack: cancel"></confirmation-modal>
<!-- /ko -->
I've showed confirmation in save there are some changes... But here I've missed case case when no changes and user click on Cancel button (in my case nothing happens).
So how can I combine 2 directives - click (for case with no changes) and toggleClick (for case when there are some changes) ?
Thanks.
You can simply have a single function on click event and then inside the function compare if there is a change that needs to be asked.
Here is a simple example : https://jsfiddle.net/kyr6w2x3/110/
HTML:
<form data-bind="visible:ShowForm">
<input type="text" data-bind="textInput:Input">
<input type="button" value="Cancel" data-bind="click:CancelForm">
</form>
<div data-bind="text:Status">
</div>
JS:
var MainViewModel = function() {
var self = this;
self.Input = ko.observable();
self.Status = ko.observable();
self.ShowForm = ko.observable(true);
self.canSave = ko.observable(false);
self.Input.subscribe(function(newValue){
if(newValue){
self.canSave(true);
}
})
self.CancelForm = function(){
if(self.canSave()){
self.Status("there is a change that needs to be asked the user");
}else{
self.ShowForm(false);
self.Status("there is no change so the form got hidden")
}
}
};
ko.applyBindings(new MainViewModel ());

ng-model doesn't change value when field contains user input

I'm still fairly new to angular.js. This seems like it should be very simple, but I'm stumped.
I have an input field:
<input type="text" placeholder="Search" ng-model="search.txt">
And I have a button that calls this function in my controller on ng-click:
$scope.clearSearch = function() {
$scope.search = {txt:"qqqqq"};
}
Clicking the button behaves as expected - the input value on the page becomes "qqqqq". So the data binding seems correct.
However, if I type anything into the field first and then press the button, the input value does not change on the page - the input field keeps the value I typed. Why is that?
What I'm really trying to do is clear the field, I'm just using "qqqqq" for illustration - setting the value to null has the same behavior.
It works:
Script:
angular.module('myapp',[])
.controller('myctrl',function($scope){
$scope.search = {text:'some input'};
$scope.clearSearch = function () {
$scope.search={text:null};
}
});
Markup:
<div ng-app="myapp" ng-controller="myctrl">
<input type="text" ng-model="search.text"/>
<button ng-click="clearSearch()">clear</button>
</div>
In plunker

Categories

Resources