I want to change the label of same button in angularjs according to requirement, same button can be for update and submit.
See the following demo,
Above demo is about the replicate the template. If some template has already data then label of submit button should be Update, other-wise for empty template label should be Submit.
I can't use following logic because it will change all button with same label, but I want to show label Submit only for empty and no-empty to show label Update. How I will do that?
<a class="btn btn-success" ng-click="updateOrder($index)">{{btnText}}</a>
And add some logic to your controller, that will specify text for button:
if (newItem){
$scope.btnText = 'Submit';
}else{
$scope.btnText = 'Update';
}
HTML
<div class="col-md-12" style="bottom:10px" >
<div class="form-group" ng-repeat="field in fields">
<div class="col-md-12">
<div class="col-md-4">
<label class="col-md-12 control-label">Field1</label>
<div class="col-md-12">
<input data-ng-model='field.field1' class="chosen-select input-md form-control sme-input-box"/>
</div>
</div>
<div class="col-md-4">
<label class="col-md-12 control-label">Field2</label>
<div class="col-md-12">
<input ng-model='field.field2' class="chosen-select input-md form-control sme-input-box"/>
</div>
</div>
</div>
<div class="col-md-12">
<div class="col-md-3">
<a class="btn btn-success" ng-click="removeTemplate($index)">Remove</a>
</div>
<div class="col-md-3">
<a class="btn btn-success" ng-click="updateOrder($index)">Submit</a>
</div>
</div>
</div>
<div class="col-md-3" style="top:5px">
<a class="btn btn-success" ng-click="cloneTemplate()">Add</a>
</div>
</div>
Angularjs
$scope.fields=[
{
"field1": "",
"field2": "",
}
]
// update and get invoice details
$scope.cloneTemplate=function(){
var clone_template={ "field1": "", "field2": ""};
$scope.fields.push(clone_template);
}
$scope.removeTemplate= function(templateIndex){
$scope.fields.splice(templateIndex,1);
}
$scope.updateOrder=function(i){
var updateOrder={
"field1":$scope.fields[i].field1,
"field2":$scope.fields[i].field2,
}
alert(updateOrder.field1);
$http.post(config.server, updateOrder)
.success(function(response, status){
console.log(response);
})
.error(function(response, status){
console.log(response);
})
}
I understand that while while adding data you wanted to show Submit button label & show Update button label while updating record.
So as normal practice you are getting this value from the DB, so I'd suggest you to add id column in this object which will be there with fields. Now object will look like {id: 1, field1: '1', field2: 2} so if the element has id that means it has persisted in the database. And obviously if you don't have id in fields record means it has been added from UI.
So the whole logic will look at the id property of your object, if you have id in the record then it will show Update as button label otherwise it would be Submit
<div class="col-md-3">
<a class="btn btn-success" ng-click="updateOrder(field)"
ng-bind="field.id? 'Update': 'Submit'">
Submit
</a>
</div>
So for make your logic working good, you need to get the list again from the database to make your UI consistent.
Working Plunkr
Change your markup for button to show some scope property:
<a class="btn btn-success" ng-click="updateOrder($index)">{{btnText}}</a>
And add some logic to your controller, that will specify text for button:
if (newItem){
$scope.btnText = 'Submit';
}else{
$scope.btnText = 'Update';
}
Related
i'm trying to store a user input from a form and then use that variable on a different page.
It seems like it should be very simple but im getting absolutely nothing back and i cant work out why.
Code on page 1:
<div class="container-fluid d-flex justify-content-center" id="mySearchBar">
<div class="row d-flex justify-content-center ">
<h3 class="heading text-center pt-5">Search the Title Below and Find The Site It's Hosted On!</h3>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search this blog" id="searchbar" name="searchbar ">
<script> localStorage.setItem('loan', document.getElementById("searchbar").value );</script>
<div class="input-group-append">
<button class="btn btn-secondary" id='searchButton' type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
Then on page two i have the following:
<script>
var loan = localStorage.getItem('searchbar');
console.log(loan);
</script>
Any help would be appreciated!
In order to fetch a value entered by the user you must do so after they enter the value. You need to use an event listener to fetch and store the value. For your use-case it would be best to wrap your inputs in a <form> and listen for the form submit. That way you capture the submit button's click and/or the input's enter key press.
You are using bootstrap-4 so I will assume you have jQuery imported as well.
<form class="container-fluid d-flex justify-content-center" id="mySearchBar">
<div class="row d-flex justify-content-center ">
<h3 class="heading text-center pt-5">Search the Title Below and Find The Site It's Hosted On!</h3>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search this blog" id="searchbar" name="searchbar">
<div class="input-group-append">
<button class="btn btn-secondary" id='searchButton' type="submit">
<i class="fa fa-search"></i>
</button>
</div>
</div>
</div>
</form>
<script>
// use a constant key string on both pages
const searchbar_local_storage_key = 'my_unique_key_for_searchbar_value'
// on page where you need to fetch stored value
$(document).ready(function() {
let stored_value = localStorage.getItem(searchbar_local_storage_key)
console.log('searchbar localStorage value at document.ready:')
console.log(stored_value)
})
// on page where you need store/overwrite the value
$(document).ready(function() {
let $searchbar = $('#searchbar')
console.log('searchbar input value at document.ready:')
console.log($searchbar.val())
$('#mySearchBar').on('submit', function(event) {
console.log('searchbar form submitted')
// stop form submission if needed
event.preventDefault()
// get the current value
let term = $searchbar.val()
console.log('searchbar input value at form.submit:')
console.log($searchbar.val())
// store values
localStorage.setItem(searchbar_local_storage_key, $searchbar.val());
console.log('new searchbar value in localStorage:')
console.log(localStorage.getItem(searchbar_local_storage_key))
})
})
</script>
See it in action here https://jsfiddle.net/chan_omega/qt510oms/
Enter a value, submit, view the output in the console and then reload the page (to simulate being on a different page). You will see the same value loaded from localStorage.
I need to show an error message if No Radio Button is selected in the Model Form. I am getting Values into the radio form and now want to show a message that "Please select a Resume first" if no Resume is selected.
Following is the code for Model form in which I am showing the Radio Button:
<div class="modal fade" tabindex="-1" id="ResumeModal" role="dialog" ng-controller="topCtrl">
<div class="modal-dialog modal-sm">
<div class="modal-content ">
#using (Html.BeginForm("ApplyJob", "PostedJob", FormMethod.Post))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
x
</button>
<h4 class="modal-title">Choose Your Resume</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<input type="hidden" name="PostedJobId" id="PostedJobById" value="#Model.PostedJobId" />
<input type="hidden" name="CreatedBy" id="CreatedBy" value="#Model.CreatedBy" />
#foreach (var item in NurseOneStop.WebSite.Models.ApplicationSession.CurrentUser.NurseResumeList)
{
<div class="col-md-12 lstCard">
<input type="hidden" name="CheckedResumeId" id="CheckedResumeId" />
<input type="radio" name="RBCheckedResume" style="height: 15px; width: 18px;" onchange="CheckedResume(#item.ResumeId)" /> <span>#item.ResumeName</span>
</div>
}
</div>
<span style="color:Red">{{msg}}</span>
#*<label id="lblMessage" style="color:red"></label>*#
</div>
</div>
<div class="modal-footer">
<span style="color:Red">{{msg}}</span>
<button id="btnSubmitResume" type="submit" class="btn btn-primary pull-right" ng-click="userAlertResumeSubmit()">
Submit
</button>
</div>
}
</div>
</div>
</div>
Below is the code for JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#btnShowModal").click(function (){
$("#ResumeModal").modal('show');
});
});
function CheckedResume(id) {
$('#CheckedResumeId').val(id);
console.log($('#CheckedResumeId').val());
};
</script>
This is how I did it on a website recently. Please note, you should swap out the 'UIKit.notification' for something else if you are not using UIKit already on the website.
$('.btnSubmitResume').submit(function(e){
if ($("input[name=RBCheckedResume]:checked").length === 0) {
e.preventDefault();
UIkit.notification({
message: 'Please check at least one box to continue',
status: 'primary',
pos: 'top-right',
timeout: 5000
});
}
});
Also please note, you should not be using an ID within a for loop like id="CheckedResumeId". This will create multiple ID's of the same type and cause issues for you. I'd advise changing this to a class
ID attribute for an HTML element should be unique. In the code snippet which you've shared, duplicate hidden form elements with ID 'CheckedResumeId' will be created which will pollute the HTML DOM. You can take the element outside of foreach and check the code. Like Below
<input type="hidden" name="CheckedResumeId" id="CheckedResumeId" />
#foreach (var item in NurseOneStop.WebSite.Models.ApplicationSession.CurrentUser.NurseResumeList)
{
<div class="col-md-12 lstCard">
<input type="radio" name="RBCheckedResume" style="height: 15px; width: 18px;" onchange="CheckedResume(#item.ResumeId)" />
<span>#item.ResumeName</span>
</div>
}
Here goes the JS to check if radio button is clicked when executing the onsubmit function.
if($('#CheckedResumeId').val().trim() == "") {
//Give an error message to user saying that the radio button is not clicked.
}
The setup.
I am using MVC 5, and I have created a view with data sent in the form of a viewmodel.
With in this view I have rendered a List object as stacked div's, as seen below.
As you will see, I am displaying hidden fields, so that the viewModel send back the data to the controller on submit.
<div class="row item-row">
<div class="small-4 columns">
objType
</div>
<div class="small-6 columns">
<input id="object_0__Id" name="object[0].Id" type="hidden" value="999999">
<input id="object_0__Reference" name="object[0].Reference" type="hidden" value="myRef">myRef
<input id="object_0__RecordChanged" name="object[0].RecordChanged" type="hidden" value="NoChange">
</div>
<div class="small-2 columns remove-item">
<button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(999999);">Remove</button>
</div>
</div>
<div class="row item-row">
<div class="small-4 columns">
objType
</div>
<div class="small-6 columns">
<input id="object_1__Id" name="object[1].Id" type="hidden" value="000001">
<input id="object_1__Reference" name="object[1].Reference" type="hidden" value="myRef">myRef
<input id="object_1__RecordChanged" name="object[1].RecordChanged" type="hidden" value="NoChange">
</div>
<div class="small-2 columns remove-item">
<button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(000001);">Remove</button>
</div>
</div>
Ok, so the javascript function RemoveItem is:
function RemoveItem(id)
{
event.preventDefault();
var element = $(event.target).closest('.item-row');
$(element).closest('DeedReference_0__RecordChanged').val('Deleted'); ***** This is what I am trying to do.
$(element).hide();
}
From the above, when I click on say RemoveItem(00001), the variable element contains the following:
<div class="small-4 columns">
objType
</div>
<div class="small-6 columns">
<input id="object_0__Id" name="object[0].Id" type="hidden" value="000001">
<input id="object_0__Reference" name="object[0].Reference" type="hidden" value="myRef">myRef
<input id="object_0__RecordChanged" name="object[0].RecordChanged" type="hidden" value="NoChange">
</div>
<div class="small-2 columns remove-item">
<button class="button tiny expand centre button-gray" onclick="javascript: RemoveItem(000001);">Remove</button>
</div>
The value I need to update is object[0].RecordChanged, but at this moment in time, I do not know the index value. So I was planning on using the ends with selector, but am not able to get it to work.
I have got as far as:
$(event.target).closest('.item-row').children()[1]
But this gives me the div, since I have tried:
$(event.target).closest('.item-row').children()[1].Find('Id*"__RecordChanged"')
$(event.target).closest('.item-row [id*="RecordChanged"]')
$(event.target).closest('.item-row:[id*="RecordChanged"])
And using the variable
$(element [id*="RecordChanged"])
$(element [id$="RecordChanged"])
UPDATE
Fixed bug in code that was suggesting that I was looking at the wrong index.
Also, If I click the remove button for RemoveItem(000001), I am trying to update the value object_0__RecordChanged.
Changed view model to have an index property. Then changed placed the HTML.EditorFor within a foreach loop enabling me to populate the index property before it is rendered out.
Then the code was changed from:
function RemoveItem(id)
{
event.preventDefault();
var element = $(event.target).closest('.item-row');
$(element).closest('DeedReference_0__RecordChanged').val('Deleted'); ***** This is what I am trying to do.
$(element).hide();
}
to:
function RemoveItem(id)
{
event.preventDefault();
var recordChanged = '#object_' + id + '__RecordChanged';
$(recordChanged).val('Deleted');
var element = $(event.target).closest('.item-row');
$(element).hide();
}
Much simpler!
I try to achieve the following functionality. Have editable form inputs in an angular application. For example a user can see his first name being fetched by the server and then clicking an edit button the form text input appears, edit button disappears and in its place the buttons save and cancel appear. I use the angular-bootstrap-show-errors component to show errors.
However when a validation rule is not fulfilled during editing and I click on cancel button the form tries to show the error before going back to the starting state. For example, I press edit and delete all the first name characters, then press cancel, so before disappearing it tries to validate. Below is my view.
<!--First name edits-->
<div class="row">
<form name="firstNameEditForm" role="form" novalidate>
<div class="col-xs-3">
<p class="text-right">First Name:</p>
</div>
<div class="col-xs-6" ng-if="model.beforeFirstNameEdit">
<p class="text-success">
{{accountData.firstname || "Loading..."}}
</p>
</div>
<div class="col-xs-6" ng-if="!model.beforeFirstNameEdit">
<div class="form-group" show-errors>
<input name="firstName" ng-model="accountData.firstname" class="form-control" placeholder="First Name" type="text" required minlength=2 auto-focus />
<small class="help-block" ng-if="firstNameEditForm.firstName.$error.required">At least 2 characters required</small>
<small class="help-block" ng-if="firstNameEditForm.firstName.$error.minlength">At least 2 characters required</small>
</div>
</div>
<div class="col-xs-3" ng-if="model.beforeFirstNameEdit">
<button type="button" class="btn btn-warning btn-xs" ng-click="editFirstName()">Edit</button>
</div>
<div class="col-xs-3" ng-if="!model.beforeFirstNameEdit">
<button type="button" class="btn btn-success btn-xs" ng-click="update(accountData.firstname)">Save</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="cancelFirstNameEdit()">Cancel</button>
</div>
</form>
</div><!--First name edits-->
And the controller
$scope.preFirstNameEditModel = {};
$scope.editFirstName = function() {
// Copy preedited data locally
$scope.model.beforeFirstNameEdit = false;
$scope.preFirstNameEditModel = angular.copy($scope.accountData.firstname);
}
$scope.cancelFirstNameEdit = function(){
$scope.model.beforeFirstNameEdit = true;
$scope.accountData.firstname = angular.copy($scope.preFirstNameEditModel);
};
How can I completely avoid validation when I click on cancel button? I read some answers on similar questions suggesting to change the type of button to type = "button" but still doesn't solve my issue.
The validation of the fields is triggered on focus lost, whichis causing the validation message. You can prevent this behaviour by using ng-show="submitted && firstNameEditForm.firstName.$error.required" and ng-show="submitted && firstNameEditForm.firstName.$error.minlength". This causes the message showing up only when the form is submitted.
Furthermore you have to change the type of the update button to submit.
I have an form in my web app that is displayed via data-toggle. I'm altering the behavior of the submit event because I want to submit data without reloading the page. I can submit the form successfully and the toggle folds as expected, but afterwards, I can no longer collapse the form to use it again. What am I doing wrong?
Here is how I control the submit event
$('form').submit(function(event){
//event.preventDefault();
console.log('submit ' + $("input[name=personName]").val());
//console.log('submit ' + $('#personName').val());
//socket.emit('add', $('#personName').val());
socket.emit('add', $("input[name=personName]").val());
//$('#personName').val('');
$("input[name=personName]").val('');
//$("#add-person-panel").toggle();
$("div[id=add-person-panel]").toggle();
$("div[id=add-person-panel]").addBack('aria-expanded','false');
//$("input[name=personName]").toggle();
//$('#add-person-panel').attr('aria-expanded','');
//socket.emit('add', $('input[name=personName]'));
//$('input[name=personName]').val("");
return false; //do not let the page refresh on submit
});
form
<div class="panel panel-default">
<div class="panel-heading">
<%
if (hasKioskPermissions === true || hasDigmaKioskPermissions === true){ %>
<a data-toggle="collapse" href="#add-person-panel" class="collapsed">
"Add Person To Local Queue"
::after
</a>
<% } else { %>
<a data-toggle="collapse disabled" href="#add-person-panel" class="collapsed">
"Add Person To Local Queue"
::after
</a>
<%}%>
</div>
<div id="add-person-panel" class="panel-body collapse">
<form data-parsley-validate="" class="form-horizontal">
<div class="form-group">
<div class="col-sm-5 col-xs-8">
<input name="personName" type="text" maxlength="40" placeholder="Enter name" required class="form-control" autocomplete="off">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" data-loading-text="Adding..." class="btn btn-lg btn-block btn-primary">Add</button>
</div>
</div>
</form>
</div>
</div>
Use $('div#add-person-panel') instead of $("div[id=add-person-panel]").
What is the template type? It's not plain html. There are <% %> in the code.
Are you trying to use server-side sockets in browser (socket.emit(...))?
UPD
Did you initialize your socket before using?
There is an example from docs:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' }); });
</script>
The problem was that I was not using the same plugin (from bootstrap) to close as I did with open. This is necessary since the plugin tracks it's own state.
before:
$('div#add-person-panel').toggle();
after:
$('div#add-person-panel').collapse('hide');
minimal solution below:
$('form').submit(function(event){
event.preventDefault();
console.log('submit ' + $("input[name=personName]").val());
$("input[name=personName]").val('');
$('div#add-person-panel').collapse('hide');
$('div#add-person-panel').addBack('aria-expanded','false');
return false; //do not let the page refresh on submit
});