Consume an endpoint using optional parameters in angularjs - javascript

I have a form with 2 sections. From each section, at least one value must be selected.
I know how to pass compulsory parameters but passing the appropriate parameters based on user selection is what I am not sure of.
Any ideas please?
Template plunker here
<form>
<div>
<label>Section 1</label></br>
<input type="checkbox" name="chkBox1" value="chkBox1">chkBox1<br>
<input type="checkbox" name="chkBox2" value="chkBox2">chkBox2<br>
<input type="checkbox" name="chkBox3" value="chkBox3">chkBox3<br>
</div>
<div>
<label>Section 2</label>
<div>
Optional 1:
<input type="text" name="fname" value="fname" />
</div>
<div>
Optional 2:
<input type="text" name="lname" value="lname" />
</div>
</div>
<button ng-click="getAll()">Get result</button>
</form>
Controller function
$scope.getAll = function() {
return $http.get('/api/testing?chbox1='+ 1 +'&chbox3=' + 1
+'&chbox2=' + 0 +'&optional1=' + fname +'&optional2=' + lname);
},

You can concat your URL depending of fname & lname defined or not:
return $http.get('/api/testing?chbox=' + 1 + '&chbox3=' + 1 + '&chbox2=' + 0 + ((fname !== undefined) ? '&optional1=' + fname : '') + ((lname !== undefined) ? '&optional2=' + lname : ''));
},
I used ternary conditions for writing it faster, but you can use multiple conditions for this case too:
$scope.getAll = function(){
var url;
if (fname !== undefined && lname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional1=' + fname +'&optional2=' + lname;
else
if (fname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional1=' + fname;
if (lname !== undefined)
url = '/api/testing?chbox1='+ 1 +'&chbox3=' + 1 +'&chbox2=' + 0 +'&optional2=' + lname;
}
Second option is less elegant!

Related

Prompt User for Input but display Input on Form

Good Morning,
Does anyone know how to correct the code below? First, I prompt the user for the variables first and second but am failing to have them display on the form. Second, when the user clicks on the Determine the larger number button it is supposed to run the if and else if statement located under the function determineLarge(){ but it fails to run. My apologies as I am learning at the university to code this language. Thank you for the help.
<script>
function determineLarge(){
let first = prompt ("Enter the first number.");
first= document.myForm.first.value;
let second = prompt("Enter the second number.");
second =document.myForm.first.value;
first = parseFloat(first);
second = parseFloat(second);
let message = "";
if (first <0 || second <0){
message = "You can't use negative numbers.";
}
else if (first > second){
message = "The second number" + "(" + second + ")" + " is smaller.";
}
else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
else if (first == second || second==first){
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
</script>
</head>
<body>
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="" onclick="javascript:determineLarge();">
<p>Enter the second number</p>
<input type="number" name="second" value="" onclick="javascript:determineLarge();">
<button type="button" onclick="determineLarge();">Determine the larger number</button>
</form>
<div id="results"> </div>
</body>
I separated the getting of the values and processing of them into two functions.
I put the prompts in a while loop so you are forced to enter in a real value greater than zero.
Also you overwrite the first and second variables by keeping the variable name first ie: first = .... instead of document.myform.value == first etc..
first = -1;
second = -1;
function getValues(){
while(isNaN(first) || first == "" || first < 0){
first = prompt ("Enter the first number.");
}
while(isNaN(second) || second == "" || second < 0){
second = prompt ("Enter the second number.");
}
document.myForm.first.value = first;
document.myForm.second.value = second;
}
function determineLarge(){
let message = "";
if (first > second){
message = "The second number" + "(" + second + ")" + " is smaller.";
}
else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
else if (first == second || second==first){
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="" onclick="javascript:getValues();">
<p>Enter the second number</p>
<input type="number" name="second" value="" onclick="javascript:getValues();">
<button type="button" onclick="determineLarge();">Determine the larger number</button>
</form>
<div id="results"> </div>
I removed the prompt so that the inputs can be used. No need to call onClick on the text input.
<script>
function determineLarge(myForm) {
var first = myForm.first.value;
var second = myForm.second.value;
console.log(first, second)
first = parseFloat(first);
second = parseFloat(second);
let message = "";
if (first < 0 || second < 0) {
message = "You can't use negative numbers.";
} else if (first > second) {
message = "The second number" + "(" + second + ")" + " is smaller.";
} else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
} else if (first == second || second == first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
</script>
</head>
<body>
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="">
<p>Enter the second number</p>
<input type="number" name="second" value="">
<button type="button" onclick="determineLarge(this.form);">Determine the larger number</button>
</form>
<div id="results"> </div>
</body>

how to serialize a form under specific conditions

Taka a look at this fiddle here this is a form where a business user enters the offered services.I sent the data with ajax and by serializing the form.
Click edit and add(plus sign) a service...in the example an input is added where it's name attribute value is of this **form= form[5]...**contrast with this with the form of the name attribute value in the other inputs...only the newly added services have the name attribute like this and the reason for that is to serialize only these...and not the others already present in the DOM/stored in the DB.
And now my problem:
Imagine that the user goes to edit the already registered services(or that he goes to edit them and add a new one)...at this case the already registered services wont'be serialized cause of the form the name attribute value has...(and the reason for this is explained above).
What can I do in this case?Sometimes I must serialize only part of a form and sometimes whole of the form.If all the inputs have name attribute value of form[1....] then along with the newly added input...already registered services will be serialized again.
Thanks for listening.
Code follows(you can see it in the fiddle too)
$('.editservices').click(function() {
//console.log(('.wrapper_servp').length);
originals_ser_input_lgth = $('.services').length;
var originals = [];
$('.show_price')
// fetch only those sections that have a sub-element with the .value
class
.filter((i, e) => $('.value', e).length === 1)
// replace content in remaining elements
.replaceWith(function(i) {
var value = $('.value', this).data('value');
var fieldsetCount = $('#serv').length;
var index = fieldsetCount + i;
return '<div class="show_price"><p id="show_p_msg">Price
visibility</p></div>' + '\
<div class="show_p_inpts">' +
'<input class="price_show"' + (value == 1 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="1">yes' +
'<input class="price_show"' + (value == 0 ? "checked" : "") + '
type="radio" name="form[' + index + '][price_show]" value="0">no' +
'</div>'; // HTML to replace the original content with
});
$('#buttons').removeClass('prfbuttons');
$('#saveserv').addClass('hideb');
$('.actionsserv').removeClass('actionsserv');
priceavail = $(".price_show:input").serializeArray();
});
$('#addser').on('click', function() {
$('#saveserv').css('border','2px solid none');
var serviceCount = $('input.services').length + 1;
var serv_inputs = '<div class="wrapper_servp"><div class="serv_contain">\n\
<input placeholder="service" class="services text" name="form[' + serviceCount + '][service]" type="text" size="40"> \n\
<input placeholder="price" class="price text" name="form[' + serviceCount + '][price]" type="text" size="3"></div>';
var p_show = '<div class="show_p">' +
'<p id="show_p_msg">Price visibility;</p>' +
'<span id="err_show_p"></span><br>' +
'</div>';
var inputs = '<div class="show_p_inpts">' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="1">yes' +
'<input class="price_show" type="radio" name="form[' + serviceCount + '][price_show]" value="0">no' +
'</div></div>';
$('.wrapper_servp').last().after(serv_inputs + p_show + inputs);
$('#saveserv').removeClass('hideb');
$('#remser').css('display', 'inline');
});
$('#cancelserv').click(function(e) {
e.preventDefault();
//var newinputs = $('.wrapper_servp').length;
//var inp_remv = newinputs - originals_ser_input_lgth;
//$('.wrapper_servp').slice(-inp_remv).remove()
$('.show_p_inpts')
.filter((i, e) => $('.price_show:checked', e).length === 1)
.replaceWith(function(i) {
var value = $('.price_show:checked').attr('value');
return '<span data-value="' + value + '" class="value">' + (value == 1 ? "yes" : "no") + '</span>'
});
});
var groupHasCheckedBox = function() {
return $(this).find('input').filter(function() {
return $(this).prop('checked');
}).length === 0;
},
inputHasValue = function(index) {
return $(this).val() === '';
};
$('#saveserv').click(function(e) {
e.preventDefault();
//from here
var $radioGroups = $('.show_p_inpts');
$('.show_p_inpts').filter(groupHasCheckedBox).closest('div').addClass("error");
$('.services, .price').filter(inputHasValue).addClass("error");
//to here
var $errorInputs = $('input.services').filter((i, e) => !e.value.trim());
if ($errorInputs.length >= 1) {
console.log($errorInputs);
$('#err_message').html('you have to fill in the service'); return;
}
if ($('input.price').filter((i, e) => !e.value.trim()).length >= 1) {
$('#err_message').html('you have to fill in the price'); return;
}
});
var IDs=new Array();
$('body').on('click', '#remser', function(e){
var inputval=$('.services:visible:last').val();
if(inputval!=='')
{r= confirm('Are you sure you want to delete this service?');}
else
{
$('.wrapper_servp:visible:last').remove();
}
switch(r)
{
case true:
IDs.push($('.services:visible:last').data('service'));
$('.wrapper_servp:visible:last').addClass('btypehide');
if($('.serv_contain').length==1)$('#remser').css('display','none');
$('#saveserv').removeClass('hideb').css('border','5px solid red');
//originals.servrem=true;
break;
case false:var i;
for(i=0;i<originals.ser_input_lgth;i++)
{
$('input[name="service'+i+'"]').val(services[i].value);
$('input[name="price'+i+'"]').val(prices[i].value);//εδω set value
}
$('.services').slice(originals.ser_input_lgth).remove();
$('.price').slice(originals.ser_input_lgth).remove();
$('.openservices').addClass('hide').find('.services,.price').prop('readonly', true);
var text='<p class="show_price">Θες να φαίνεται η τιμή;<span data-value="'+ show_pr_val.value +'" class="value">' +(show_pr_val.value==1 ? 'yes':'no') + '</span></p>';
$('.show_p_inpts').remove();
$('.show_price').replaceWith(text);;
break;
}
});
I have an Idea for you. What you can do is when you show the currently existed value in you html instead of giving name attribute just give data-name attribute. I.e
Change this
<input class="services text" data-service="21" size="40" value="hair" type="text" name="service0" readonly="">
To This
<input class="services text" data-service="21" size="40" value="hair" type="text" data-value="hair" data-name="service0" readonly="">
Now when user update this values you can bind an event in jQuery like below.
$(document).ready(function(){
$(".services input").on("change paste keyup", function() {
if($(this).val() === $(this).attr("data-value"))
{
$(this).removeAttr("name");
}else{
$(this).attr("name",$(this).attr("data-name"));
}
});
});
By this way you can give name attribute to only those elements whose values are changed. Now each time you can serialize the whole form and it will only get the value of changed elements.
Don't forget to give unique class to already existed elements so you can bind on change event. Hope its clear to you.

converting value returned from js function

The following js returns an error as below when trying to complete a conditional statement if( asset_type.indexOf("true,false") >= 0 )
I have tried to convert asset_type to string... and all fail
Error:
asset_type.get is not a function
the folowing code does return
console.log("Asset Type (row " + i + "): " + asset_type );
Asset Type (row 12): true,false
Code:
$("#myTable_asset").children("tbody").children("tr").each(function (i) {
var $this = $(this);
var my_td = $this.children("td");
var second_col = my_td.eq(1);
var third_col = my_td.eq(2);
second_col.find("input[type=text]").val(function(i, val) {
return val.replace(/\$|,/g, '');
});
var asset_value = second_col.find("input[type=text]").val();
var asset_type = third_col.find(":checkbox").map(function(_, el) { return el.checked }).get()
console.log("Asset Type (row " + i + "): " + asset_type );
try {
if ( '' != asset_type)
{
console.log("Asset Cost (row " + i + "): " + parseFloat(asset_value));
console.log("Asset Type (row " + i + "): " + asset_type );
if( asset_type.indexOf("true,false") >= 0 )
{
capex_value += parseFloat(asset_value);
}
if(asset_type.get().indexOf("false,true") >= 0 )
{
opex_value += parseFloat(asset_value);
}
}
}
catch(err) {
console.log(err.message);
}
});
a print out of third_col.html() gives the following:
<fieldset data-role="controlgroup" data-type="horizontal" class="ui-controlgroup ui-controlgroup-horizontal ui-corner-all">
<div class="ui-controlgroup-controls ">
<div class="ui-checkbox ui-mini">
<label for="asset_allocation_capex_19" class="ui-btn ui-corner-all ui-btn-inherit ui-checkbox-off ui-first-child">
Capex
</label>
<input type="checkbox" name="asset_allocation_capex_19" id="asset_allocation_capex_19" data-mini="true">
</div>
<div class="ui-checkbox ui-mini">
<label for="asset_allocation_opex_19" class="ui-btn ui-corner-all ui-btn-inherit ui-checkbox-on ui-btn-active ui-last-child">
Opex
</label>
<input type="checkbox" name="asset_allocation_opex_19" id="asset_allocation_opex_19" data-mini="true" checked="">
</div>
</div>
</fieldset>
asset_type is an array of [true, false].
You cant do get() or indexOf('true,false').
You can do:
var first = asset_type[0], scond = asset_type[1];
if(first=== true && second === false){...}
else if(first=== false && second === true){...}
I think that you forgot that you already used get() on jquery elements here:
var asset_type = third_col.find(":checkbox").map(function(_, el) {
return el.checked }).get()
Just check your code.

Validate dynamically generated input box with dynamic ID and name

I have a button that adds two input field onclick. Below is the code:
<button type="button" class="btn btn-warning btn-xs" id="additem">
Click here to add Items</button>
<form>
<div id="inputboxes"></div>
<input type="submit">
</form>
and JQuery is
var i = 1,
j = 1,
k = 1,
l = 1;
$("#additem").click(function () {
$("#inputboxes").append("<div class='form-group'><input type='text' id='iname" +
(j++) +
"' name='iname" +
(i++) +
"' class='form-control' placeholder='Enter Item Name' required='required'/></div> " +
"<div class='form-group'><input type='text' id='iprice" +
(k++) +
"' name='iprice" +
(l++) +
"' class='form-control' placeholder='Enter Item Price' required='required'/></div>");
})
How can i validate these dynamically added input boxes for empty and correct values on submitting the form?
You can do something like:
$('.form-group').each(function(){
var input = $(this).children('input');
if(input.val() == '' || input.val() == undefined){
// the errors you will give
}else{
if(input.attr('id').substring(0, 5) == 'iname'){
//function to validate your iname
}else if(input.attr('id').substring(0, 6) == 'iprice'){
//function to validate your iprice
}
}
});

View page does not recognize null element in load

I have an javascript function that generates links in my page based on a DropDown. I'm checking the javascript function in two places; when the DropDown changes with attribute "onchange", and when the page is loaded. The error is generated when the page is loaded without element on viewbag, my javascript is not recognizing the null element for generate links without the information on viewbag.
<p>Pesquisar por: #Html.DropDownList("tipoPesquisa", ViewBag.DropDownPesquisa as SelectList, new { onchange = "alteraFiltro()" })
<div id="dadosFornecedor">
#if (ViewBag.CurrentFornecedor != null)
{
<fieldset>
<legend>#ViewBag.CurrentFornecedor.RazaoSocial</legend>
<b>Razão Social:</b> #ViewBag.CurrentFornecedor.RazaoSocial <b>Endereço:</b> #ViewBag.CurrentFornecedor.Endereco
#Html.Hidden("idFornecedor", new { IdFornecedor = ViewBag.CurrentFornecedor.IdFornecedor })
<input type="button" class="btn" onclick="removerFornecedor();" value="Remover Fornecedor" />
<br />
<br />
</fieldset>
<br />
}
</div>
<script type="text/javascript">
$(function () {
alteraFiltro();
});
function removerFornecedor() {
var div = $("#dadosFornecedor");
var hidden = $("#idFornecedor");
div.empty();
div.append("<input type='hidden' name='deletarFornecedor' value='true' />")
}
function alteraFiltro() {
var urlCodigo = $("#linkCodigo");
var urlLancamento = $("#linkLancamento");
var urlPagamento = $("#linkPagamento");
var urlFornecedor = $("#linkFornecedor")
var dropValue = $("#tipoPesquisa").val();
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
} else{
urlCodigo.attr("href", "saidasDiversas?sortOrder=#ViewBag.CodigoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlLancamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataLancamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlPagamento.attr("href", "saidasDiversas?sortOrder=#ViewBag.DataPagamentoSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
urlFornecedor.attr("href", "saidasDiversas?sortOrder=#ViewBag.FornecedorSortParm&idFornecedor=#ViewBag.CurrentFornecedor.IdFornecedor&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "")
}
}
</script>
If the issue is caused by ViewBag.CurrentFornecedor not having a value when the view is first loaded, try altering your javascript along these lines:
var hidden = $("#idFornecedor");
if (hidden.val() == "" || hidden.val() == null || hidden == null) {
// ...
}
else {
urlCodigo.attr("href", "saidasDiversassortOrder=#ViewBag.CodigoSortParm&idFornecedor="
+ #{ViewBag.CurrentFornecedor != null ? ViewBag.CurrentFornecedor.IdFornecedor : -1}
+ "&currentFilter=#ViewBag.CurrentFilter&currentDrop=" + dropValue + "");
// ...
}

Categories

Resources