getting a default value to display in a div - javascript

currently when the page loads the defualt value of 10 displays which is what I want like so:
the custom amount shows:
but if I type something in the custom area and then delete it no default value is displayed. As shown here:
How can I get 10 to show up even if the user deletes their custom amount. I basically want 10 to always show if the user doesn't enter an amount or click a another button
here is my js:
$(document).ready(function() {
$('#donation-amount').keyup(function() {
$('#display-amount').text($(this).val());
});
$( ".selectvalue" ).click(function() {
$('#display-amount').text($(this).val());
});
$(".buttons .btn").click(function(){
$(".buttons .btn").removeClass('active');
$(this).toggleClass('active');
});
$('#display-amount').text($('#default').val());
});
and my html:
<div class="choose-pricing">
<div class="btn-group">
<div class="buttons">
<button type="button" id="default" class="btn btn-default selectvalue hover-color active" value="10">10</button>
<button type="button" class="btn btn-default selectvalue hover-color" value="15">15</button>
<button type="button" class="btn btn-default selectvalue hover-color" value="20">20</button>
<input type="Custom" name="donation-amount" class="inpt-first form-control" id="donation-amount" onclick="if(this.defaultValue == this.value) this.value = ''" onblur="if(this.value=='') this.value = this.defaultValue" value="Custom">
</div>
<input type="hidden" name="donation-amount-value" id="donation-amount-value">
</div>
<div class="money-donate">
<div class="display-amount" id="display-amount">
</div>
</div>
</div>
any help would be appreciated!

You can do this
store default in global and then apply when value is empty.
var defaultValue = 10;
$('#donation-amount').keyup(function() {
if($(this).val()) {
$('#display-amount').text($(this).val());
} else {
$('#display-amount').text(defaultValue );
}
});
See in action here http://jsbin.com/guxukodace/edit?html,js,output

Related

How to increase checkbox values ​with jquery?

When the button is pressed, we clone the email field. Checkbox values ​​conflict. How can I solve this problem? I would be glad if you help. I hope I can.
$('.add-extra-email-button').click(function() {
$('.clone_edilecek_email').clone(true, true).appendTo('.clone_edilen_email');
$('.clone_edilen_email .clone_edilecek_email').addClass('single-email remove-email');
$('.single-email').append('<div class="btn-delete-branch-email"><button class="remove-field-email btn btn-danger"><i class="fas fa-trash"></i></button></div>');
$('.clone_edilen_email > .single-email').attr("class", "remove-email");
$('.clone_edilen_email input').each(function() {
if ($(this).val() == "") {
$(".add-extra-email-button").attr("disabled", true);
} else {
$(".add-extra-email-button").attr("disabled", true);
}
$(".remove-email:last").find('.email-address').val('');
});
});
<div class="col-md-6">
<div class="clone_edilecek_email">
<div class="form-group">
<label for="name">E-posta</label>
<div class="input-group">
<input type="email" class="form-control email-address" name="email[]" placeholder="E-Posta giriniz">
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-secondary">
<input type="checkbox" name="ban[]" value="1" autocomplete="off">
<span class="fas fa-ban"></span>
</label>
<label class="btn btn-secondary">
<input type="checkbox" name="circle[]" autocomplete="off">
<span class="fas fa-exclamation-circle"></span>
</label>
</div>
</div>
</div>
</div>
<div class="text-left">
<button type="button" class="add-extra-email-button btn btn-success" disabled><i class="fas fa-plus"></i></button>
</div>
<div class="clone_edilen_email"></div>
</div>
you must set the index between the brackets, like this:
<input type="checkbox" name="circle[0]" autocomplete="off"> <span class="fas fa-exclamation-circle"></span>
Why? otherwise only the selected checkboxes will be send and the backend. The browser will only send that 2 checkboxes are checked to the backend/server. the server than has no idea which of the checkbox indexes where checked. thats why in the frontend you need to provide an index for each checkbox.
Warning: not all backends understand these kind of form names (but most do).
you could do this like this::
var index =1;
$('input').each(function(inputElement) {
// execute the function for each input element. (might want to do the same for select elements.
// take the name of that element
var name = $(inputElement).prop('name');
// replace [] with the index you want// (warning this only works if you dont use multi dimensional arrays.
var newName = name.relace('[]','['+index+']');
// replace the old name with the new name.
$(inputElement).prop('name',newName);
});
note you can use a function like this:
function setIndeces(container, index){
$('input',container).each(function(inputElement){
var name = $(inputElement).prop('name');
var newName = name.relace('[]','['+index+']');
$(inputElement).prop('name',newName);
});
}
setIndeces($('newAddedDiv', 1);

Manipulating button in a custom input file

When i use more than one input files, the remove button only works on first input. The intention is to be able to use several inputs without the action in one of them changing the rest. It seems that the code is not seeing the different IDs of the inputs. How do I make them see which input is undergoing changes, noting the ID of each?
function bs_input_file() {
$(".input-file").find('input').each(function (index, dom) {
var id = dom.id;
$("#" + id).parent().find("button.btn-reset").addClass("hidden");
$(".input-file").before(
function () {
if (!$(this).prev().hasClass('input-ghost')) {
var element = $("<input type='file' id='" + id + "' class='input-ghost' style='visibility:hidden; height:0'>");
element.attr("name", $(this).attr("name"));
element.change(function () {
element.next(element).find('input').val((element.val()).split('\\').pop());
});
$(this).find("button.btn-choose").click(function () {
element.click();
});
$(this).find("button.btn-reset").click(function () {
element.val(null);
$(this).parents(".input-file").find('input').val('');
bs_input_file();
});
$(this).find('input').css("cursor", "pointer");
$(this).find('input').mousedown(function () {
$(this).parents('.input-file').prev().click();
return false;
});
console.log(element)
return element;
}
}
);
$("#" + id).change(function () {
var element = $("#" + id);
if (element.val() != "") {
$("#" + id).parent().find("button.btn-reset").removeClass("hidden");
} else {
$("#" + id).parent().find("button.btn-reset").addClass("hidden");
}
})
})
}
bs_input_file();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h3>Example</h3>
<form method="POST" action="#" enctype="multipart/form-data">
<!-- COMPONENT START -->
<div class="form-group">
<div class="input-group input-file" name="Fichier1">
<input id="fileInput0" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group input-file" name="Fichier2">
<input id="fileInput1" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<!-- COMPONENT END -->
</form>
</div>
</div>
I dont quite understand, but if you call a function via click event, you can pass in an event object. This has an attribute called target which has an attribute called id
function clicked(event){
console.log(event.target.id)
}

Modal in asp.net view not working properly

In my strongly typed view I am looping over a list of objects coming from a database. Each of these objects is presented in a jumbotron, which has a button "Had role before". On click the modal opens and there I want to input some data in input boxes and save it to my database via an ajax call. One part of data that I want to input is the unique id which each object in the loop has. With the code I have so far I managed on click to get the id of the first object, but when I am clicking the buttons for the rest of the objects nothing happens.
This is the script in my view :
<script type="text/javascript">
$(document).ready(function () {
$(function () {
var idW;
$('#mdl').on('click', function () {
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="mdlname"]').val();
var id = parent.find('input[name="mdlwrid"]').val();
var idW = id;
console.log(idW);
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
$('#myModal').modal('show');
});
});
$('#mdlSave').on('click', function () {
console.log('x');
addPastRoleAjax();
});
function addPastRoleAjax() {
$.ajax({
type: "POST",
url: '#Url.Action("addPastRole", "WorkRoles")',
dataType: "json",
data: {
wrId: idW,
dateStart: $("#wrdateStart").val(),
dateEnd: $("#wrknamedateEnd").val()
},
success: successFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
</script>
the loop :
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="mdlwrid" value="#item.WorkRoleId" />
<input type="hidden" name="mdlname" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" id ="mdl" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
The modal :
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
<input id="wrdateStart" class='date-picker' />
<input id="wrknamedateEnd" class='date-picker' />
</div>
<div class="modal-footer">
<button type="button" id="mdlSave" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
Your problem is in the following piece of code:
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="mdlwrid" value="#item.WorkRoleId" />
<input type="hidden" name="mdlname" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" id ="mdl" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
You have used a foreach loop and inside it you create button elements with same id.
<button type="button" id ="mdl" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button>
So,foreach let you to create many buttons with same id. That's wrong and that's why you get that behavior(only first button work).The solution: Use classes instead.

Deleting dynamic input fields in Vue

Noob question but I can get fields to render in Vue but not sure how to delete my fields. I added an index option in the v-for directives but not sure what to do after that. Thanks!
Here is a working JSFiddle: https://jsfiddle.net/xu55npkn/
<body>
<div id="app"></div>
<script>
const createNewOption = () => {
return {
text: '',
isAnswer: false
}
}
const createNewQuestion = () => {
return {
text: '',
options: [createNewOption()]
}
}
var vm = new Vue({
el: '#app',
template: `<div class="quiz-builder container">
<div v-for="question in questions">
<div class="input-group">
<input type="text" class="form-control" v-model="question.text" placeholder="Enter a question">
<span class="input-group-btn">
<button class="btn btn-danger" type="button">X</button>
</span>
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" #click="addOption(question)">Add an option</button>
</span>
</div>
</br>
<div class="input-group" v-for="(option, index) in question.options" style="margin-bottom: 20px">
<span class="input-group-addon">
<input type="checkbox" v-model="option.isAnswer">
</span>
<input type="text" class="form-control" v-model="option.text" placeholder="Enter an option">
<span class="input-group-btn">
<button class="btn btn-danger" type="button">X</button>
</span>
</div></br>
</div>
<button class="btn btn-default" #click="addQuestion" :disabled="questions.length >= 5 ? true : false">
Add another question
</button>
<button class="btn btn-primary" style="background-color: #ffcc00; border: #ffcc00">
Create quiz
</button>
</div>`,
data () {
return {
questions: [createNewQuestion()],
showQuestions: false,
}
},
methods: {
addQuestion () {
this.questions.push(createNewQuestion())
},
removeQuestion (index) {
this.questions.shift(index)
},
addOption (question) {
question.options.push(createNewOption())
}
}
})
</script>
Based on your updated question, you have already solved for removing questions, although yev's answer is a much better way for removing questions.
To remove options, you need to add a new handler for removeOption that takes in both the question (which you are iterating over) and the option (which you are iterating over. Vue handles both of these scenarios for you. You can then find the index of the option and splice the array. See this fiddle.
template:
<button class="btn btn-danger" type="button" #click="removeOption(question, option)">
X
</button>
component:
removeOption (question, option) {
var index = question.options.indexOf(option);
if (index > -1) {
question.options.splice(index, 1);
}
}
Your delete button should look like:
<div v-for="(question, i) in questions">
<div>
<input v-model="question.text">
<span>
<button #click=removeQuestion(i)>X</button>
</span>
<span>
<button #click="addOption(question)">Add an option</button>
</span>
</div>
</div>
Notice I've added i (index) in your for loop and click handler for X button.
Your remove function will look like:
removeQuestion (index) {
this.questions.splice(index, 1);
}
Array.shift will remove only first item in the array which is not exactly what you want :)

AngularJS can't pass $index from bootstrap modal window

I'm banging my head against the wall here. I'm using ng-repeat to populate a table. Inside each row i have 2 buttons, one for updating the row content and for uploading files. The upload button opens a bootstrap modal window, where the user selects the files and clicks on submit.
The submit button uses ng-click to run a function which uses $index as parameter. But the $index value is always the same no matter which row is selected.
The thing I don't understand is that I use the exact same syntax (although outside of a modal window) on my update button, which works just fine.
HTML:
<tr ng-repeat="item in items | filter:search " ng-class="{'selected':$index == selectedRow}" ng-click="setClickedRow($index)">
<td>{{$index}}</td>
<td ng-hide="idHidden" ng-bind="item.Id"></td>
<td ng-hide="titleHidden">
<span data-ng-hide="editMode">{{item.Title}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="item.Title" data-ng-required />
<td>
<button type="button" class="btn btn-primary uploadBtn" data-ng-show="editMode" data-toggle="modal" data-target="#uploadModal">Upload file <i class="fa fa-cloud-upload"></i></button>
<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="uploadModalLabel">Options</h3>
</div>
<div class="modal-body">
<h4>Upload Documents</h4>
<form>
<div class="form-group">
<select data-ng-model="type" class="form-control" id="fileTypeSelect">
<option value="Policy">Policy</option>
<option value="SOP">SOP</option>
</select>
<br>
<div class="input-group"> <span class="input-group-btn">
<input type="file" id="file">
</span>
</div>
<br>
<button type="button" class="btn btn-default" data-ng-click="uploadAttachment($index, type)">Upload</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<button type="button" data-ng-hide="editMode" data-ng-click="editMode = true;" class="btn btn-default pull-right">Edit <i class="fa fa-pencil-square-o"></i></button>
<button type="button" data-ng-show="editMode" data-ng-click="editMode = false; updateItem($index)" class="btn btn-default">Save</button>
<button type="button" data-ng-show="editMode" data-ng-click="editMode = false; cancel()" class="btn btn-default">Cancel</button>
</td>`
JS:
$scope.uploadAttachment = function executeUploadAttachment(index, type) {
var listname = "Risk Register";
var id = $scope.items[index].Id;
console.log(indexID);
readFile("uploadControlId").done(function(buffer, fileName) {
uploadAttachment(type, id, listname, fileName, buffer).done(function() {
alert("success");
}).fail(function() {
alert("error in uploading attachment");
})
}).fail(function(err) {
alert("error in reading file content");
});
}
So the function uploadAttachment($index, type) which is triggered by ng-click doesn't pass the right index number. It always passes the same, no matter what row it is clicked in.
I have omitted some of the code that is irrelevant. If needed i can provide the whole thing.
Any suggestions to what I am missing?
Edit:
I have tried to implement DonJuwe suggestions.
I have added this inside my controller:
$scope.openModal = function(index) {
var modalInstance = $modal.open({
templateUrl: 'www.test.xxx/App/uploadModal.html',
controller: 'riskListCtrl',
resolve: {
index: function() {
return index;
}
}
});
};
This is my modal template:
<div class="modal-header">
<h3 class="modal-title" id="uploadModalLabel">Options</h3>
</div>
<div class="modal-body">
<h4>Upload Documents</h4>
<form>
<div class="form-group">
<select data-ng-model="type" class="form-control" id="fileTypeSelect">
<option value="Policy">Policy</option>
<option value="SOP">SOP</option>
</select>
<br>
<div class="input-group"> <span class="input-group-btn">
<input type="file" id="file">
</span>
</div>
<br>
<button type="button" class="btn btn-default" data-ng-click="uploadAttachment($index, type)">Upload</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
And finally my function which resides inside RiskListCtrl (the only controller i use):
$scope.uploadAttachment = function executeUploadAttachment(index, type) {
var listname = "Risk Register";
var id = $scope.items[index].Id;
console.log(indexID);
readFile("uploadControlId").done(function(buffer, fileName) {
uploadAttachment(type, id, listname, fileName, buffer).done(function() {
alert("success");
}).fail(function() {
alert("error in uploading attachment");
})
}).fail(function(err) {
alert("error in reading file content");
});
}
It seems that $scope.items[index].Id is empty. Error: Cannot read property 'Id' of undefined
The modal window has its own scope. That means you need to resolve data you want to pass into the modal's scope. To do so, use resolve within the modals open(options) method.
Before I will give you an example, I want to suggest having only one modal for all your table items. This will let you keep a single template where you can easily use id (now, you create a template for each of your table items which is not valid). Just call a controller function and pass your $index:
<button type="button" class="btn btn-primary uploadBtn" data-ng-show="editMode" ng-click="openModal($index)">Upload file <i class="fa fa-cloud-upload"></i></button>
In your controller, create the modal instance and refer to the template:
$scope.openModal = function(index) {
var modalInstance = $modal.open({
templateUrl: 'myPath/myTemplate.html',
controller: 'MyModalCtrl',
resolve: {
index: function() {
return index;
}
}
});
};
Now you can access index in your MyModalCtrl's scope by injecting index:
angular.module('myModule', []).controller('MyModalCtrl', function($scope, index) {
$scope.index = index;
});
Since, you are getting the index value outside model then you can also use ng-click and then call a function in your controller and store the index value in a temporary variable and then when you are using submit button then just take make another variable and assign the value of temporary variable to your variable. for example:
<button type="button" data-ng-show="editMode" data-ng-click="editMode = false; updateItem($index)" class="btn btn-default">Save</button>
and then make a function in your controller
$scope.updateItem = functon(index)
{
$scope.tempVar = index;
}
now use the value of tempVar in you function
$scope.uploadAttachment = function executeUploadAttachment(index, type) {
var index = tempVar; //assign the value of tempvar to index
var listname = "Risk Register";
var id = $scope.items[index].Id;
console.log(indexID);
readFile("uploadControlId").done(function(buffer, fileName) {
uploadAttachment(type, id, listname, fileName, buffer).done(function() {
alert("success");
}).fail(function() {
alert("error in uploading attachment");
})
}).fail(function(err) {
alert("error in reading file content");
});
}

Categories