I'm trying to build a query parameter for when doing a search, I managed to build it with input field however there's a select dropdown menu to select other values.
<input type="text" class="dd">
<select name="" class="sel">
<option value=""></option>
<option value="Prepare">Prepare</option>
<option value="Ready">Ready</option>
<option value="Cancel">Cancel</option>
</select>
<button onclick="buildQuery()">Build query</button>
jQuery code for query building the query param
function buildQuery(){
var result = "?";
var getVal = $('input.dd').val();
console.log('Input > ', getVal);
var getSelectVal = $('select.sel').val();
if (getVal != null && (getVal != "")) {
let inputValues = getVal
.split("\n")
.filter(function (str) { return str !== "" })
.join("&test=");
// then add it to the overall query string for all searches
result = result + 'test' + "=" + inputValues + "&";
console.log('Results > ', result);
}
Not sure how can I get the value from the select and construct it similar way to my input console.log output Results > ?test=f&
So if you fill in the input and select an option it the queryParam should say something like ?test=inputVal&test=selectVal or individual ?test=inputVal or ?test=selectVal
What I can do is copy the whole if() statement and replace the getVal with getSelectVal but it seems inefficient and duplicating the code.
Actual code --
newSearchParams.properties.forEach(function (inputSearch) {
// first reparse the input values to individual key value pairs
// Checks which field is not null and with empty string (space)
var getVal = $('input.input_' + inputSearch.name).val();
var getSelectVal = $('select.select_' + inputSearch.name).val();
if (getVal != null && (getVal != "")) {
let inputValues = getVal
.split("\n")
.filter(function (str) { return str !== "" })
.join("&" + inputSearch.name + "=");
// then add it to the overall query string for all searches
result = result + inputSearch.name + "=" + inputValues + "&";
}
}, this);
// remove trailing '&'
result = result.slice(0, result.length - 1);
return result;
Sample Fiddle
Edit: -- This is what I'm trying to get out of this question,
if(paramMethod == 'path'){
// build parameter api/id/1
} else if(paramMethod =='query'{
// build queryString api/apiPoint?id=1
} else if(paramMethod == 'none') {
// var result = "";
// return result;
}
If you're not worrying about IE < 9:
function buildQuery() {
return $('.dd, .sel')
.toArray()
.reduce(function(str, el) {
return str + (el.value ? el.name + '=' + el.value + '&' : '')
}, '?')
}
Working fiddle: https://jsfiddle.net/qk3d7bq1/2/
If you care about IE < 9:
function buildQuery() {
var query = '?'
$('.dd, .sel').each(function() {
if (this.value) {
query += this.name + '=' + this.value + '&'
}
})
return query
}
Working fiddle: https://jsfiddle.net/d51f5uyw/2/
Update
If you want to make this generically useful, just pass a selector string to buildQuery to select the exact things you want:
function buildQuery(selector) {
return $(selector)
.toArray()
.reduce(function(str, el) {
return str + (el.value ? el.name + '=' + el.value + '&' : '')
}, '?')
}
Fiddle: https://jsfiddle.net/qsxkz4qu/1/
Alternatively you could specify a container and have buildQuery find all of the form fields inside that container:
Fiddle: https://jsfiddle.net/uar5h3xe/1/
But buildQuery itself should not be defining any selection variables. That's configuration that should be passed to it.
Update
If you want to parameterize the whole thing, you could use something like what's shown at this fiddle: https://jsfiddle.net/uar5h3xe/4/
Related
I have a select like this:
<select class="form-control" ng-hide="Catalogos.length==0"
ng-change="filtro(selected)" ng-model="selected"
ng-options="item.Nombre for item in Catalogos ">
</select>
From there I get selected value in function like this:
$scope.filtro = function(selected) {
$scope.selectedID = selected.ID;
}
There I get Id for selected value, but now I use it into another function, but that function can get parameter null or not so function is:
$scope.insertar = function () {
if ($scope.catalogoid != null) {
var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
if ($scope.selected.ID != null) {
url = url + "/" + $scope.selected.ID;
}
apiService.post(url....
Problem is when it comes null it just throw $scope.selected is undefined when it pass this validation
if ($scope.selected.ID != null) {
url = url + "/" + $scope.selected.ID;
}
How can I validate it if $scope.selected doesn´t exist in this case?
you stored it in $scope.selectedID but retrieving from $scope.selected.ID.
Use
if ($scope.selectedID != null) {
I have a recusive function that is supposed to loop through a json object and output the expression. However, my recusion seems to be off because it's outputting field1 != '' AND field3 == '' when it should be outputting field1 != '' AND field2 == '' AND field3 == ''
I've tried a couple different things and the only way I can get it to work is by creating a global variable outstring instead of passing it to the function. Where am I off? When I step through it, i see a correct result but once the stack reverses, it start resetting outstring and then stack it back up again but leaves out the middle (field2).
JSFiddle
function buildString(json, outstring) {
var andor = json.condition;
for (var rule in json.rules) {
if (json.rules[rule].hasOwnProperty("condition")) {
buildString(json.rules[rule], outstring);
} else {
var field = json.rules[rule].id;
var operator = json.rules[rule].operator;
var value = json.rules[rule].value == null ? '' : json.rules[rule].value;
outstring += field + ' ' + operator + ' ' + value;
if (rule < json.rules.length - 1) {
outstring += ' ' + andor + ' ';
}
}
}
return outstring;
}
var jsonObj = {"condition":"AND","rules":[{"id":"field1","operator":"!= ''","value":null},{"condition":"AND","rules":[{"id":"field2","operator":"== ''","value":null}]},{"id":"field3","operator":"== ''","value":null}]};
$('#mydiv').text(buildString(jsonObj, ""));
The function has a return of a string.
When you call the function recursively from within itself, you aren't doing anything with the returned string from that instance, just calling the function which has nowhere to return to
Change:
if (json.rules[rule].hasOwnProperty("condition")) {
buildString(json.rules[rule], outstring);
}
To
if (json.rules[rule].hasOwnProperty("condition")) {
// include the returned value in concatenated string
outstring += buildString(json.rules[rule], outstring);
}
DEMO
Why so complicated?
function buildString(obj) {
return "condition" in obj?
obj.rules.map(buildString).join(" " + obj.condition + " "):
obj.id + " " + obj.operator + " " + string(obj.value);
}
//this problem occurs quite often, write a utility-function.
function string(v){ return v == null? "": String(v) }
I have a set of controls on my page that I am attempting to iterate through and determine if they have values. Some of these controls are <select> items and in this instance I need to loop through the options associated with the <select> control and find the ones that are selected. I have tried .children() as well as .find("option:selected") and neither of them work (both throw an "undefined" error in javascript). What am I doing wrong?
function getJsonValue(control, json) {
if(control.dataset["fieldname"] !== "undefined"){
if(control.tagName == "SELECT") {
var selected = "{";
var idName = control.dataset["idname"];
control.children.each( function() {
if(this.selected) {
selected += idName + ": " + this.val() + ",";
}
});
selected += "}";
if(selected != '') {
json += control.dataset["fieldname"] + ": ";
json += selected + ",";
}
} else {
if(control.val() != '') {
json += control.dataset["fieldname"] + ": ";
json += control.val() + ",";
}
}
}
};
The error is appearing on line 5 of the above code (control.children.each). I've tried:
control.children.each( function() {
control.childre().each( function() {
control.find("option:selected").each( function() {
None of these options work. For reference, the "control" variable is passed from another function that is found by doing the following:
$("#search-header").find("select").each( function() {
json = getJsonValue(this, json);
});
To further extend on my comment, I can see that you are passing the object this, which is assigned to the variable control in your function. However, jQuery cannot directly operate on this object unless it is converted into a jQuery object, and this can be done simply by wrapping it with the jQuery alias, $(control) (hint, just like how people use $(this) in jQuery, it's the same thing).
Therefore, if you revise your code this way, it should work:
function getJsonValue(control, json) {
if(control.dataset["fieldname"] !== "undefined"){
if(control.tagName == "SELECT") {
var selected = "{";
var idName = control.dataset["idname"];
$(control).children.each( function() {
if(this.selected) {
selected += idName + ": " + this.val() + ",";
}
});
selected += "}";
if(selected != '') {
json += control.dataset["fieldname"] + ": ";
json += selected + ",";
}
} else {
if(control.val() != '') {
json += control.dataset["fieldname"] + ": ";
json += $(control).val() + ",";
}
}
}
};
p/s: On a side note, if you ever want to access the original DOM node from a jQuery object, just use $(control)[0] ;)
Try
$(control).find("option:selected").each( function() {
or
$(control).children.each( function() {
You are passing (this) to you function from the caller. It doesn't have jquery selector.
You are missing Open close bracket on first children
control.children().each( function() {
control.childre().each( function() {
control.find("option:selected").each( function() {
I have a symbol (#) seperated variable as shown below
var inputStr = "IceCreams#Cone";
How can i split this and form a string in java script variable .
With the above input String how can form a string as
Are You Sure to add a Category Under IceCreams => Cone
I have tried as shown below ,but couldn't achive that dynamically
Thanks in advance .
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under" +res[0]+" "+res[1]+" );
if (r == true) {
} else {
}
}
http://jsfiddle.net/4km0k9nv/1/
You code works if you fix your typo.
window.onload = function() {
function myFunction(inputStr) {
var res = inputStr.split('#');
alert("Are You Sure to add a Category Under " + res[0] + " " + res[1] + " ?" );
}
myFunction("Ice#cream");
}
If you just want to replace the "#" symbol, you can use the string replace function.
var str = "part1#part2";
var str2 = str.replace('#', " => ");
Your example should work fine, but it seems to be a typo.
Good Luck
I was messing around with it and I came up with this. Is this what you want? It runs the function on the input element blur.
function myFunction(inputStr)
{
var res = inputStr.split('#');
confirm("Are You Sure to add a Category Under " + res[0] + " => " + res[1] + " ?");
}
<input type="text" onblur="myFunction(this.value)">
Hope this helps!
function myFunction(inputStr)
{
var res = inputStr.split('#');
var r = confirm("Are You Sure to add a Category Under " + res[0] + " => "+ res[1] + "?");
if (r == true) {
addNewCategory(res[0], res[1]); // rename/rewrite this call as needed
} else {
cancelAdd(); // replace this line with whatever you need.
}
}
Alternatively you can say:
var res = inputStr.replace("#", " => ");
var r = confirm("Are You Sure to add a Category Under " + res + "?");
The second bit of code would make res a string instead of an array of strings. Depending on your needs, that may suffice. If you'd like to or need to use res as an array of strings, then the first chunk of code should be all your need.
PFB java script code..
the thing is im getting alert for duplicate entry. how can avoid the repeated data?
Var activityconunt =0;
if (activityconunt !== data.iRoundId) {
alert("duplicate");
$("#selectRound_Type").append("<option name='round' id=" + data.iRoundId + ">" + data.strRoundName + "</option>");
}
my output
Solution one:
Take your data and build a clean array before. Using http://api.jquery.com/jquery.inarray/
Solution two:
Check your existing options for containing values
if($("option:contains('" + data.strRoundName + "')").length == 0)
$("#selectRound_Type").append("<option name='round' id=" + data.iRoundId + ">" + data.strRoundName + "</option>");
this should do it as well and is a shorter code
also see Fiddle
Use an array to store the data and check the new value with it:
$(function () {
var items = [];
var $select = $('select');
var $input = $('input');
var $button = $('button');
// fetch current data
$select.find('option').each(function () {
items.push($(this).text());
});
$button.on('click', function () {
var value = $input.val();
var exists = ($.inArray(value, items) != -1);
if (! exists) {
items.push(value);
$('<option></option').text(value).prependTo($select);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<button>Add</button>
<br />
<select style="width: 300px;">
<option>Hello</option>
</select>
Solution for preventing duplicate values and undefined value in the list
if ($("option:contains('" + data.strRoundName + "')").length == 0
&& data.strRoundName != null
&& typeof data.strRoundName != "undefined")
$("#selectRound_Type").append("<option name='round' id="
+ data.iRoundId + ">"
+ data.strRoundName + "</option>");