Clear input ng-model when ng-show is false AngularJS - javascript

Hi I have a small problem.
I have an input bar which sometimes need to be shown in a form and sometimes not.
I am afraid that if someone put data and then hide it and press send, the data will be sent. So I want to reset the input each time it is hidden.
ng-change isn't a good idea because it doesn't let my write anything.
<div class="form-group" ng-show="isItOne=='1' || isItTwo=='2'">
<label class="col-md-1">someName</label>
<div class="col-md-4">
<input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
</div>
</div>
and this is the function
$scope.clearWhenChanged = function() {
$scope.nameModel = "";
};

take out the show condition and use it to control visibility and model value.
$scope.showHideField = function(){
if(isItOne=='1' || isItTwo=='2'){
return true;
}
$scope.nameModel= "";
}
call it in your div:
<div class="form-group" ng-show="showHideField()">
this also provides the flexibility to pass a flag based on which you can decide whether to clear the field's value or not .. :)

You could call a function instead where you set the isItOne variable. In that function you could set the variable to 1 or 2 and clear the model value.
HTML
<div class="form-group" ng-show="show()">
<label class="col-md-1">someName</label>
<div class="col-md-4">
<input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
</div>
</div>
Controller
$scope.show = function() {
if ($scope.isItOne == '1' || $scope.isItOne == '2');
return true;
$scope.nameModel = '';
}
Having said all that it might be a better option to just simply unset the model's value on submit in cases when you don't want it to be sent.

use the tag attribute ng-if="your condition", This will render the tag only when the condition is true. Otherwise it will remove the whole input from DOM.

Related

Angular checkbox to filter data

I am showing FreeEvents using checkbox. I am passing the value to the filter as filter:filterFreeEvent . This is working fine.
But I want to avoid passing value in the filter rather I want to use a change event of a checkbox to filter.
Something like
<input type="checkbox" ng-model="showFreeEvent" ng-change($event)">
This is my JsFiddle example.
Has anyone done something like this?. Any help or suggestion would be appreciated.
Thanks in advance
You can also change a variable in the change-event only like this :
<input ng-model="changeValue" ng-change="showFreeEvent = showFreeEvent== false ? true : false" value="" type="checkbox" />
If the showFreeEvent is false, ng-change will change it to true and vice-versa.
You can use ng-change to handle the checkbox change event. Then you can use Array.prototype.filter to filter your events. Filtered events should be stored in a separate variable. Here is an example of how to do this:
<input ng-model="showFreeEvents" type="checkbox" ng-change="onShowFreeEventsChanged()" />
<div ng-controller="myCtrl">
<div ng-repeat="event in filteredEvents">
<span>{{event.eventName}}</span></br>
<span>{{event.eventStartDateTime}}</span></br>
<span>{{event.itemCreatedDateTime}}</span></br>
</br></br>
</div>
</div>
Then in your controller:
$scope.showFreeEvents = false;
$scope.events = [ /* here you should store unfiltered events */ ];
$scope.filteredEvents = filterEvents($scope.events);
// whenever showFreeEvents checkbox value changes, re-filter the events
$scope.onShowFreeEventsChanged = function() {
$scope.filteredEvents = filterEvents($scope.events);
};
function filterEvents(events) {
return events.filter(function(event) {
// Here you should write your filtering logic.
// I'd recommend to remove such comparisons, as these are prone to errors.
// \
return !$scope.showFreeEvents || event.eventName === 'Event 9';
});
}

ng-repeat not updating information after $scope was updated

I have an ng-repeat which creates a form with some starting data. Then the user is free to modify said data and the changes should appear in the form. Before that, the user submitted data are sanitized by another function, which is called by an ng-click on a button.
Everything works well under the hood (I checked my $scope.some_array, from which ng-repeat takes the data and the new data is in the right place) but nothing happens on the page.
The element:
<li ng-repeat="field in some_array" id="field-{{$index}}">
<div class="{{field.field_color}}">
<button type="button" ng-click="save_field($index)">done</button>
{{field.nice_name}}
</div>
<div id="field-input-{{$index}}">
<input type="text" id="{{field.tag}}" value="{{field.content}}">
<label for="{{field.tag}}">{{field.nice_name}}</label>
</div>
</li>
save_field code:
$scope.save_field = function (index) {
console.log($scope.some_array[index]["content"])
var value = $("#field-" + index).children("div").children("input").val()
var name = $scope.some_array[index]["name"]
var clean_value = my_clean(value)
if (norm_value === "") {
return
}
$scope.some_array[index]["content"] = clean_value
console.log($scope.some_array[index]["content"])
}
On the console I see:
10.03.16
10/03/16
Which is right, but in the form I only see 10.03.16. I already tried putting $timeout(function(){$scope.$apply()}) as the last line of my function, but the output is still the same.
You shouldn't use input like this if you want to bind a variable to it. Digest loop will refresh the value but it will not be updated visibly because this is not html native behavior.
Use ng-model instead, it will update view value of the input as expected:
<input type="text" id="{{field.tag}}" ng-model="field.content">
Also using ng-model your variable will be updated when user modify the input, so you can retrieve it to do some treatments much more easily in save_field function, without jQuery:
$scope.save_field = function (index) {
if (norm_value === "") {
return;
}
$scope.some_array[index]["content"] = my_clean($scope.some_array[index]["content"]);
};
More infos: https://docs.angularjs.org/api/ng/directive/ngModel

javascript "if else" wont go in else when condition is not met

I have an input text and an empty label in html
<div class="form-group">
<label for="hsDetailsForm-name">Denumire</label>
<input id="hsDetailsForm-name" type="text" class="form-control" ng-model="hydroStation.name" placeholder="Obligatoriu" required ng-blur="validationObliga()" autofocus/>
<label id="obliga"></label>
</div>
and here is the function in js
$scope.validationObliga = function () {
var value = $.trim($("hsDetailsForm-name").val());
if (value == "") {
$('#obliga').html("Campul este obligatoriuu!").css("color", "red");
} else {
$('#obliga').html("");
}
}
ng-blur works and when empty it writes "Campul este obligatoriuu!" in red, however when you type something in the text field and focus out of it, it still says that, it doesnt change the label to "". Why don't it go in the else ?
The error here is you've missed # of the id selector.
Although, adding # in the selector will solve your problem, I won't recommend you to use jQuery here, use AngularJS as follow
Controller:
$scope.validationObliga = function () {
var value = $scope.hydroStation.name.trim();
$scope.showMessage = value === "";
};
View:
<div class="form-group">
<label for="hsDetailsForm-name">Denumire</label>
<input type="text" class="form-control" ng-model="hydroStation.name" placeholder="Obligatoriu" required ng-blur="validationObliga()" autofocus/>
<label ng-show="showMessage" class="error">Campul este obligatoriuu!</label>
<!-- ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^ Add this --->
</div>
CSS:
.error {
color: red;
}
You missed the anchor here; should be...
var value = $.trim($("#hsDetailsForm-name").val());
... so that you look for an element with id equal to hsDetailsForm-name. As it stands, you look for an element hsDetailsForm-name - and there's none. As result, jQuery element is empty, its val() is undefined, and $.trim(undefined) results in an empty string.

Is it possible to repeatedly use the same text box to get input from users in HTML & Javascript?

So I have a created a text box using html code along with a button for "confirm"
<input type="text" id="myInput" style="height: 10px; width: 50px" value="">
<button onclick="enter_value()">Confirm</button>
What I intend to do is to use the same text box over and over for different inputs as the website guides the user to do different tasks (which all functions are written in js)
I'm trying to figure out a way to use this same text box for all inputs users have to insert, but so far nothing is working.
I tried creating a function like:
function enter_value(){
var name = document.getElementById("myInput").value;
}
This should be able to store the value of the input in the variable name. Problem is, I want to execute this when button is pressed, but the button is not responding and the variable "name" always returns "Enter Your Input Here" (is this default?)
What am I missing here?
You can definitely re use the same text box to take in more than one piece of information. The question is how do you store the info in the process. So you can keep the onclick handler that you already have, then change what you do with the input based on the state of the page.
Current Step: <div id="current_step">name</div>
<input type="text" id="myInput" style="height: 10px; width: 50px" value="">
<button onclick="enter_value()">Confirm</button>
<div class="results">
<div id="name_result"></div>
<div id="addr_result"></div>
</div>
function enter_value(){
var curStep = document.getElementById("current_step").innerHTML,
curValue = document.getElementById("myInput").value;
//do some error testing here, if it is a bad submission dont continue
if (curValue == "") return false;
if (curStep == "name"){
document.getElementById("name_result").innerHTML = curValue
document.getElementById("current_step").innerHTML = "address"
}
else if (curStep == "address"){
document.getElementById("addr_result").innerHTML = curValue
document.getElementById("current_step").innerHTML = "Done!"
}
document.getElementById("myInput").value = '';
}
You should be able to use this to get started

Set the default value of an input text

my requirement is to save the entire "html" inside a div, but when i load an "html" with text fields to a div and then editing the value of the text box, the newly set value doesn't reflect in the core "html". I tried to inspect the value with fire bug and it remains the same or no value at all.With "jquery" i tried to set attribute but no attribute name value is created. how can i set the value of text fields and then get that "html" with the newly set value.
here is my html
<div class="sub_input_box">
<input type="text" / class="boreder_line">
<input type="text" id="txt" value=""/>
<input type="hidden" id="hid" />
<div class="clear"></div>
</div>
and the jquery i used to set attribute
$("#txt").attr("value", "some value");
Chances are you're calling your jQuery code before the HTML input part. You can either place the jQuery stuff below it, or if you don't want to, you can do something like this:
$(document).ready(function(){
$("#txt").attr("value", "some value");
});
That will only run when the page is fully loaded.
However, it's unclear if you're using AJAX to load those inputs into your DOM. If so, you need to call $("#txt").attr("value", "some value"); in the onSuccess callback function which is fired after the AJAX successfully responds.
You can try something like this:-
<input name="example" type="text" id="example"
size="50" value="MyDefaultText" onfocus="if(this.value=='MyDefaultText')this.value=''"
onblur="if(this.value=='')this.value='MyDefaultText'" />
Have you tried:
$("#txt").val("Hello World!");
For setting the text value, and,
var my_string = $("#txt").val();
For getting the text value.
Let me know if it works.
Excellent question. You would think clone would do this on its own, alas, it doesn't.
Here is a sample than you can hopefully adapt to do what you need
HTML
<div id=divToCopy>
<input name=i1 value=foo><br>
<input name=i2 value=bar>
</div>
<input type=button onclick=copyDiv(); value='Copy the div'>
<div id=newDiv>
the copy will go here
</div>
JavaScript
function copyDiv() {
$('#newDiv').html($('#divToCopy').clone());
$('#divToCopy :input').each(function() {
var child=0;
for (var i = 0; i < this.attributes.length; i++) {
var attrib = this.attributes[i];
var prop=$(this).prop(attrib.name);
$($('#newDiv').find(' :input')[child]).prop(attrib.name,prop);
child++;
}
});
}
But it does work: http://jsbin.com/eXEROtU/1/edit
var html = '<input type="text" id="txt" value=""/>';
$(document).ready(function() {
$("#load").click(function() {
$("#sub_input_box").html(html);
});
$("#inspect").click(function() {
alert($("#txt").val());
});
});
$(document).on('focusout','input[type="text"]',function(a){
console.log(a.target.value);
a.target.setAttribute("value",a.target.value);
});
this is the solution i found, i had to set the value attribute explicitly on loose focus from the text field

Categories

Resources