Autofilling an input field using JQuery - javascript

I have the following form:
<form method='post' id='myform'>
<div class="typeahead__container">
<div class="typeahead__field">
<input type="text" class="item" placeholder="Item" id='item' name='input_val'>
</div>
</div>
<input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>
<button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>
And the following function to handle live search:
$(document).ready(function(){
// Defining the local dataset
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
console.log(data)
let data = {
"results": [
{ "item": "First", "id": "1847" },
{ "item": "Second", "id": "4442" },
{ "item": "Third", "id": "3847" }
]
};
//LIVE-SEARCH
$(() => {
$('#item').typeahead({
source: {
data: data.results.map(record => record.item)
},
callback: {
onInit: function($el) {
console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
}
}
});
});
//END LIVE-SEARCH
});
});
I want to add another function to fill the default value of the input field item-id according to what the user chooses on the input field item. So, for example, if the user writes First, JQuery should set the default value of item-id to 1847 (see my previous block of code).
How can i do that? Am i supposed to do that inside my live search function or should i use another function?

Looking at your code, I assume you are using Bootstrap Typeahead which uses an updater callback that we can use in this situation.
I hosted this static Json to bring a solution with a close syntax.
Solution 1 : Using Bootstrap Typeahead (may be useful to someone else)
$(document).ready(function(){
$('input#item').typeahead({
source: function (query, process) {
return $.get('https://api.myjson.com/bins/hi1oo', function (data) {
//console.log(data);
//data = $.parseJSON(data);
return process(data.results);
});
},
display : 'item',
displayText: function(data){ return data.item;},
val : function(data){ return data;},
updater: function (data) {
$('#item-id').val(data.id);
return data.item;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" integrity="sha256-LOnFraxKlOhESwdU/dX+K0GArwymUDups0czPWLEg4E=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<form method='post' id='myform'>
<div class="typeahead__container">
<div class="typeahead__field">
<input type="text" class="item" placeholder="Item" id='item' name='input_val' autocomplete="off">
</div>
</div>
<input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>
<button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>
P.S : If your json is a result of a real-time search query where you look for item names and get this kind of data. Then you better change the source into something like following :
source: function (query, process) {
return $.get('inc/ajaxh.php', { query: query }, function (data) {
return process(data.results);
});
},
Solution 2 : using jQuery Typeahead
This one uses the callback onClickAfter. Notice that I made some changes on how you are mapping your data' response array and choose what to be displayed then use the item.id in the callback function.
$(document).ready(function(){
// Defining the local dataset
$.getJSON('https://api.myjson.com/bins/hi1oo', function(data) {
//LIVE-SEARCH
$(() => {
$('#item').typeahead({
source: {
//data: data.results.map(record => record.item)
data: data.results
},
display: ["item"],
callback: {
//I called it itemx to avoid confusion with available "#item"
onClickAfter: function (node, a, itemx, event) {
$('#item-id').val(itemx.id);
//alert('click');
}
}
});
});
//END LIVE-SEARCH
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha256-q6QA5qUPfpeuxzP5D/wCMcvsYDsV6kQi5/tti+lcmlk=" crossorigin="anonymous"></script>
<form method='post' id='myform'>
<div class="typeahead__container">
<div class="typeahead__field">
<input type="text" class="item" placeholder="Item" id='item' name='input_val'>
</div>
</div>
<input type="text" class="id" placeholder="ID" id='item-id' name='input_val'>
<button name="button" type="submit" class="btn btn-primary btn-sm f-14 mr-1">SUBMIT</button>
</form>

Related

Deleting form values with same name attribute

i have a problem, i want to delete some name and leave some. but the problem when i try to delete one name it deletes the first one yet you have clicked to delete the last one.
so the main point is
how can i delete or send the name value which i want to delete instead deleting the first one or all.
because they all have same name 'info' but different values.
so i want to be deleting some and leave some instead all or only on top ones
any idea how i can do this
$(document).ready(function() {
$("#remove").click(function(event) {
Execute();
});
function Execute() {
$.ajax({
type: 'POST',
url: 'remove.php',
data: {
'info': $("input[name='info']").val()
},
success: function(response) {},
error: function() {
alert("error");
}
});
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="info" value="John">
<button type='button' id='remove'> delete</button>
<input type="text" name="info" value="Jane">
<button type='button' id='remove'> delete</button>
<input type="text" name="info" value="jacobo">
<button type='button' id='remove'> delete</button>
</form>
First, use a class instead of an id for your buttons. The ID should be unique.
Second, you can grab the previous input for the clicked button (target).
$(document).ready(function() {
$('.remove').click(function(event) {
execute($(event.target).prev('input'));
});
function execute($input) {
console.log(`Deleting: ${$input.val()}`);
$.ajax({
type: 'POST',
url: 'remove.php',
data: {
'info': $input.val()
},
success: function(response) {},
error: function() {
alert("error");
}
});
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="info" value="John">
<button type="button" class="remove">Delete</button>
<input type="text" name="info" value="Jane">
<button type="button" class="remove">Delete</button>
<input type="text" name="info" value="jacobo">
<button type="button" class="remove">Delete</button>
</form>

Jqueryvalidate's .validate() method does not execute in ASP Core

I'm trying to submit the form via ajax and it works fine but there was no validation. So I've added the JQuery validation library and added the code into handler as stated in the documentation but it doesnt seem to execute
The cshtml page:
#{
ViewData["Title"] = "CreateProduct";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1 class="text-center">Create Product</h1>
<br>
<form method="post" id="formdata" asp-controller="Product" asp-action="UploadProduct">
<div class="form-group">
<p>Please provide a name for your product:</p>
<input type="text" name="Name" required />
</div>
<div class="form-group">
<p>Please provide a price for your product:</p>
<input type="number" name="Price" required />
</div>
<div class="form-group">
<p>Please provide a description for your product:</p>
<input type="text" name="Description" required />
</div>
</form>
<button class="btn btn-primary" id="subBtn">Upload Files</button>
#section scripts
{
<script>
$(function () {
$('#subBtn').click(function (e) {
var formData = $('#formdata').serialize();
$('#formdata').validate({
debug: true,
submitHandler: function () {
$.ajax({
type: 'POST',
url: '/Product/UploadProduct',
data: formData,
success: function (e) {
Toastify({
text: "Product submition successful!",
duration: 3000,
gravity: "bottom", // `top` or `bottom`
position: 'right', // `left`, `center` or `right`
backgroundColor: 'blue',//"linear-gradient(to right, #00b09b, #96c93d)",
stopOnFocus: true, // Prevents dismissing of toast on hover
onClick: function () { } // Callback after click
}).showToast();
$(':input', '#formdata')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
}
}).fail(function (e) {
//toastr.error('Product not added');
});
}
});
});
});
</script>
}
And I've added the reference to the _Layout.cshtml:
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
Once again I'd like to add that the logic is working, it's just that the validate() method doesn't execute.
The .validate() method is only used to initialize the plugin on your form. It does not belong inside of the click handler of the submit button. You should move the validate() method outside of the client handler , and serialize data inside the submitHandler event :
<script>
$(function () {
$('#formdata').validate({
submitHandler: function () {
var formData = $('#formdata').serialize();
alert("ad");
$.ajax({
type: 'POST',
url: '/Product/UploadProduct',
data: formData,
success: function (e) {
Toastify({
text: "Product submition successful!",
duration: 3000,
gravity: "bottom", // `top` or `bottom`
position: 'right', // `left`, `center` or `right`
backgroundColor: 'blue',//"linear-gradient(to right, #00b09b, #96c93d)",
stopOnFocus: true, // Prevents dismissing of toast on hover
onClick: function () { } // Callback after click
}).showToast();
$(':input', '#formdata')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
}
}).fail(function (e) {
//toastr.error('Product not added');
});
}
});
});
</script>
You can then use submit button inside form tag to trigger submit :
<form method="post" id="formdata" asp-controller="Product" asp-action="UploadProduct">
<div class="form-group">
<p>Please provide a name for your product:</p>
<input type="text" name="Name" required />
</div>
<div class="form-group">
<p>Please provide a price for your product:</p>
<input type="number" name="Price" required />
</div>
<div class="form-group">
<p>Please provide a description for your product:</p>
<input type="text" name="Description" required />
</div>
<button type="submit" class="btn btn-primary" name="submit" id="ajaxsubBtn1">Upload Files</button>
</form>

Sending user input text box value via jquery from a partial page to Controller

My partial view has a table with multiple rows with a button in each row (unique across each). When the button is pressed a jquery modal dialog is opened and the user can enter a value in a text box. That value is what i'm not able to get into a jquery variable to send to my MVC controller. All the jquery code is executed from the partial view.
I've tried every example I've seen on the web. I have code already that works, just not through a partial view.
CSHTML:
<form>
<div id="currentandnewtipamount">
<div>#Html.Label("Current Tip Amount: $")
<label for="CurrentTipAmount" ></label>
</div>
<br />
#Html.Label("Tip Edit Amount")
<input type="text" name="NewTipEditAmount" id="NewTipEditAmount" >
</div>
</form>
JQuery:
var TipEditDialog, RRN;
NewTipEditAmount = $("#NewTipEditAmount");
function SubmitTipEditAmount() {
NewTipEditAmount = $("#NewTipEditAmount").val().toString();
{
$.ajax({
type: "POST",
url: "/MyTransactions/UpdateTipAMT",
data: { 'NewTipEditAmount': NewTipEditAmount },
success: function (bool) {
//alert(bool);
}
});
}
}
Below is a working example in another part of the site that does not use a partial view.
JQuery:
var Logindialog, form;
loginusername = $("#loginusername"),
loginpassword = $("#loginpassword"),
loginnewpassword = $("loginnewpassword"),
loginconfirmnewpassword = $("loginconfirmnewpassword"),
allFields = $([]).add(loginusername).add(loginpassword);
function LoginUser() {
loginusername = $("#loginusername").val().toString();
loginpassword = $("#loginpassword").val().toString();
{
$.ajax({
type: "POST",
url: "/User/Login",
data: { 'loginusername': loginusername, 'loginpassword': loginpassword },
success: function (response) {
if (response === true) {
$("#Logindialog-form").dialog("close");
RunPasswordCheck(loginusername, loginpassword);
}
else {
alert("Something is not correct, try again please");
Logindialog.dialog("close");
}
}
});
}
}
CSHTML:
<div id="Logindialog-form" title="Log In" class="divloginformcontent">
<form class="loginformcontent">
<div id="usernameAndpassword" class="Usernamepassword">
<label for="username" class="loginfieldtext">Username</label>
<input type="text" name="loginusername" id="loginusername" class="loginfields" />
<br /><br />
<label for="password" class="loginfieldtext">Password</label>
<input type="password" name="loginpassword" id="loginpassword" class="loginfields" />
<br /><br />
</div>
<input type="submit" tabindex="-1" style="position: absolute; top: -1000px" id="LoginSubmit" /> #*tab index and style allows for the enter button to be used without messing up anything*#
</form>
**
Can you try using the Jquery in the page where Partial view is calling
instead of Inside Partial View.
**
Below is the code which ended up working for my situation. I seemed to need to have an 'id' for every element and reference them throughout the nesting in the jquery.
CSHTML:
<div id="EditTip-form" title="Edit Tip Amount" class="divloginformcontent">
<form class="loginformcontent" id="form">
<div id="currentandnewtipamount">
#Html.Label("Current Tip Amount: $") <label for="CurrentTipAmount" ></label>
<br />
#Html.Label("Tip Edit Amount")
<input type="text" name="NewTipEditAmount" id="NewTipEditAmount" class="forminput">
</div>
</form>
</div>
JQUERY:
function SubmitTipEditAmount() {
NewTipEditAmount = $('#EditTip-form #form #currentandnewtipamount #NewTipEditAmount').val();
{
$.ajax({
type: "POST",
url: "/MyTransactions/UpdateTipAMT",
data: { 'RRN': RRN, 'NewTipEditAmount': NewTipEditAmount },
success: function (bool) {
//alert(bool);
}
});
TipEditDialog.dialog("close");
}
}

Merge two forms with two radio button and one form

So I have this two forms. Each has its own action, separate fields and values, radio button and button. What I want to do is that I want to have two radio buttons and one button. What is the best solution.
<div class="span6">
<h2 class="headback" >انتخاب دروازه پرداخت</h2>
<div class="text-box" style="padding-bottom: 0px">
<form class="form-inline" method="post" id="PaymentForm" action="https://google.com" style="direction: rtl">
<input type="hidden" name="amount" value="{{payment.Amount}}"/>
<input type='hidden' name='paymentId' value='{{payment.InvoiceNumber}}' />
<input type='hidden' name='revertURL' value='http://test2.happycard.ir/payment/verify' />
<input type='hidden' name='customerId' value='{{payment.Id}}' />
<label class="radio">
<img src="/media/images/images/bank.jpg"/><br/>
<input type="radio" name="PaymentProvider" id="PaymentProvider" value="4" checked>
</label>
<ul style="text-align: right">
<li>
<input type="button" value="Proceed" ng-click="SetPrePayment();" class="btn btn-primary">
</li>
</ul>
</form >
<form class="form-inline" method="post" id="PaymentForm2" action="www.wikipedia.com" style="direction: rtl">
<input type="hidden" name="pin" value='5I8bpgGr034AmB38MPQ7'/>
<input type="hidden" name="Id" value="{{payment.Id}}"/>
<input type="hidden" name="OrderId" value="{{payment.OrderId}}"/>
<input type="hidden" name="amount" value="{{payment.Amount}}"/>
<input type='hidden' name='paymentId' value='{{payment.InvoiceNumber}}' />
<?php if(custom_config::$IPGtest==1){ ?>
<input type='hidden' name='revertURL' value="<?php echo custom_config::$Test2ParsianRevertUrlHappyBarg; ?>" />
<?php } elseif(custom_config::$IPGtest==2){ ?>
<input type='hidden' name='revertURL' value="<?php echo custom_config::$ParsianRevertUrlHappyBarg; ?>" />
<?php } ?>
<label class="radio">
<img src="/media/images/images/bank.jpg"/><br/>
<input type="radio" value="parsian" name="bankname" checked>
</label>
<ul style="text-align: right">
<li>
<input type="button" ng-click="SetPrePayment2();" value="Proceed" class="btn btn-primary">
</li>
</ul>
</form >
</div>
</div>
Spoiler alert, AngularJS is used in button's actions. I uploaded a photo to show you the output of my current code.
What I want to be like is:
This is the code for my SetPrePayment() function.
$scope.SetPrePayment=function(){
$http.post('/payment/happy_payment_register/',{ 'Amount':$scope.totalPrice,'Item':$scope.item.Id, 'Description':$scope.item.Title, 'Count':$scope.defaultQuantity })
.success(function(data, status, headers, config) {
if(data!='Fail')
{
$timeout(function() {
$scope.payment=data;
timer= $timeout(function(){
document.getElementById("PaymentForm").submit();
},10)
}, 0);
}
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
and SetPrePayment2() is :
$scope.SetPrePayment=function(){
$http.post('/payment/happy_payment_register/',{ 'Amount':$scope.totalPrice,'Item':$scope.item.Id, 'Description':$scope.item.Title, 'OrderId':$scope.item.Id, 'Count':$scope.defaultQuantity })
.success(function(data, status, headers, config) {
if(data!='Fail')
{
$timeout(function() {
$scope.payment=data;
timer= $timeout(function(){
document.getElementById("PaymentForm2").submit();
},10)
}, 0);
}
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
You can use jquery for solve this problem.
move your button, out of two forms and set an ID for that.
<button id="myButton">Submit</button>
now you can check radio buttons in jquery to submit own form.
jQuery sample code:
$( document ).ready( function() {
$( '#myButton' ).on( 'click', function() {
if ( $( '#radio_1' ).is(':checked') ) {
$( '#form_1' ).submit();
setPrePayment();
} else {
$( '#form_2' ).submit();
setPrePayment2();
}
});
});
I think there's no jQuery needed for this. You can use ng-if that shows the form based on the user selection expression.
If you need to load the template conditionally you could also use ng-include but it should be OK with ngIf.
I've added two controllers one for each form that's only needed if you have to do many things in the form or you want to have them separate.
But the same approach with ng-if will work with one form controller.
Please have a look at the demo below or in this jsfiddle.
angular.module('demoApp', [])
.controller('FormOneController', FormOneController)
.controller('FormTwoController', FormTwoController)
.controller('MainController', MainController);
function FormOneController($window) {
this.submit = function() {
$window.alert('hello from form 1');
}
}
function FormTwoController($window) {
this.submit = function() {
$window.alert('hello from form 2');
}
}
function MainController() {
var vm = this;
vm.hideForms = hideForms;
vm.forms = getFormObject();
vm.isFormActive = isFormActive;
vm.selectForm = selectForm;
vm.showForm = showForm;
activate();
function activate() {
vm.selectedForm = vm.forms[0];
}
function getFormObject() {
return [{
id: 1,
name: 'form1',
label: 'show form 1',
visible: false
}, {
id: 2,
name: 'form2',
label: 'show form 2',
visible: false
}];
}
function hideForms() {
angular.forEach(vm.forms, function(form) {
form.visible = false;
});
//console.log(vm.forms);
}
function isFormActive(id) {
return vm.selectedForm.id === id && vm.selectedForm.visible
}
function selectForm(form) {
hideForms();
vm.selectedForm = form;
}
function showForm() {
vm.selectedForm.visible = true;
//console.log(vm.selectedForm);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
<label ng-repeat="form in mainCtrl.forms">{{form.name}}
<input type="radio" name="formSelector" value="form" ng-click="mainCtrl.selectForm(form)" ng-checked="mainCtrl.selectedForm === form"></input></label>
<button ng-click="mainCtrl.showForm()">show form</button>
<form ng-if="mainCtrl.isFormActive(1)" ng-controller="FormOneController as formOneCtrl">
<button ng-click="formOneCtrl.submit()">form1 submit</button>
</form>
<form ng-if="mainCtrl.isFormActive(2)" ng-controller="FormTwoController as formTwoCtrl">
<button ng-click="formTwoCtrl.submit()">form2 submit</button>
</form>
</div>

how to get a value based on a selection in knockoutjs

I'm using knockout to get some data from an API to fill my textboxes. I want to get the unit price from the API when you select a drug. How can I do this?
<div class="control-group">
<label class="control-label">Drug:</label>
<div class="form-horizontal">
<select id="Drug_ddl" data-bind="options: drugs, optionsText: function (item) { return item.Description; }, value: selectedDrug" class="input-xlarge"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">Unit Price:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: unitPrice" step="0.01" class="input-xlarge" id="UnitPrice_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Quantity:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: quantity" step="1" class="input-xlarge" id="Qty_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Cost:</label>
<div class="form-horizontal">
<input type="text" data-bind="value: drugcost" readonly="readonly" step="0.01" class="input-xlarge" id="Cost_txt" />
<input type="button" id="AddDrugs_btn" data-bind="click: addDrug" class="btn btn-primary" value="Add" />
</div>
</div>
This is the code for the viewModel:
var claimEntryViewModel = function () {
var drugs = ko.observableArray([]);
var unitPrice = ko.observable('0.00');
var quantity = ko.observable('1');
var drugcost = ko.computed(function () {
return quantity() * unitPrice();
});
var loadDrugs = function () {
url = apiServerUrl + "Items/";
$.ajax({
url: url,
headers: { 'Access-Control-Allow-Origin': '*' },
contentType: 'application/json',
dataType: 'json',
type: 'GET',
crossDomain: true,
success: function (data) {
drugs(data);
},
error: function (data) {
console.log("Is not answered");
console.log(data);
}
});
}
var selectedDrug = ko.observable();
var addDrug = function () {
var match = ko.utils.arrayFirst(claimDrugs(), function (item) {
return selectedDrug().ID === item.Id;
});
if (!match) {
claimDrugs.push({
Id: selectedDrug().ID,
Description: selectedDrug().Description,
unitPrice: selectedDrug().SalesPrice,
quantity: quantity(),
drugcost: drugcost(),
});
} else {
errorMessage("Already exists!");
}
}
return {
drugs: drugs,
addDrug: addDrug,
selectedDrug: selectedDrug,
unitPrice: unitPrice,
quantity: quantity,
drugcost: drugcost,
}
}
someone kindly provide me with a code that can do this, i'm fairly new to knockout and don't really know how to go about this. thanks
super cool is right, subscribing is a good way to handle this.
selectedDrug.subscribe(function (newValue) {
neededInfo(getSelectedDrugInfoFromApi(newValue));
});
This will call the getSelectedDrugInfoFromApi() every time the selectedDrug observable value changes, and update the neededInfo observable.
Keep in mind not to update the selectedDrug value inside the subscribe function though, as it will create a loop.

Categories

Resources