How i should set javascript global variable to get its value properly - html

I have two html elements on my page. One is dropdown and other is text field(which is working as autocomplete).
<select id="match_engine_brand" name="match_engine[brand]" class="hidden-field"><option value="">Select Brand</option><option value="3">addidas</option>
<option value="5">cat</option>
<option value="2">nike</option>
<option value="4">panther</option>
<option value="6">tower</option></select>
while text field is
<input class="string required ui-autocomplete-input" id="match_engine_shoe_model" name="match_engine[shoe_model]" placeholder="select model of shoe using autocomplete" required="required" size="50" type="text" autocomplete="off">
My cofeescript code is below
$(document).ready ->
$("#match_engine_brand").change ->
window.flag_value = $(this).val()
alert(window.flag_value) #value display in alert
$('#match_engine_shoe_model').autocomplete
source: "/user/match_shoes/shoes?id="+window.flag_value
select: (event, ui) -> $("#match_engine_shoe_model").val(ui.item.id)
In autocomplete function
window.flag_value #give me undefined value
$('#match_engine_brand :selected').val() #give me undefined value
How i can get dropdown value in autocomplete function.
Thanks for help

You need to have an initiated value of window.flag_value. Otherwise if you don't change #match_engine_branch, this var has no value. That's the reason of undefined value.
The way to solve it is to define this var before
$(document).ready ->
window.flag_value = "something"
...
However I think it's unnecessary to use global var. Check it in function should work.
$('#match_engine_shoe_model').autocomplete ->
dropdown_value = $("#match_engine_brand").val() ? "something"

Related

How to set Vue Core UI select value

Sorry for the beginner question, I am new to Vue.js. I am using CoreUI. Documentation/Tutorials on CoreUI+Vue are scarce.
I am using the <CForm> tag and here I have a <CSelect> tag.
<CForm #submit="test" ref="form">
<CSelect
label="Pick a name"
:options="['test', 'test1', 'test2']"
v-model="testy"
/>
<CButton type="submit" size="sm" color="primary"> Submit</CButton>
</CForm>
JavaScript:
methods: {
test(e) {
console.log("test");
debugger;
e.preventDefault();
}
}
When my breakpoint is hit and I inspect this.testy it will not return the value of the select box but instead this:
I was under the impression that putting v-model on my CSelect will expose my select box under this.* and I could somehow easily get the value (?!).
For context this is rendered in the DOM:
<select id="uid-wvkj98yh6gp" class="form-control">
<option data-key="0" value="test"> test </option>
<option data-key="1" value="test1"> test1 </option>
<option data-key="2" value="test2"> test2 </option>
</select>
My question: inside my test(e) method, how can I gather the current selected value of my select box?
In the <CSelect> API docs, it lists the value prop:
value
The value of select input. Set .sync modifier to track prop changes.
It seems they don't use v-model as expected and you probably also got an error about the value prop being incorrect.
Change your select to:
<CSelect
label="Pick a name"
:options="['test', 'test1', 'test2']"
:value.sync="testy"
/>
This way you use the .sync modifier the way the guide directs.

Angular 5 ngModel changes the value in UI without saving it

In my form I have a select with a bind variable. If I try to change and save the value it works fine but if I try to change the value in my modal and instead of save it, I close the modal (so I do not save the value) in my UI I see the changed value and obviously in my DB the value is not changed.
component.html
<select class="form-control m-input" id="type" formControlName="type"
[ngClass]="{ 'is-invalid': submitted && formcontrols.type.errors }" name="type"
(change)="changeType($event, newParameter.type)"
[(ngModel)]="newParameter.type">
<option [ngValue]="'STRUCT'">STRUCT</option>
<option [ngValue]="'NUM'">NUM</option>
<option [ngValue]="'BOOLEAN'">BOOLEAN</option>
<option [ngValue]="'DATE'">DATE</option>
</select>
component.ts
changeType(event, type){
type= this.createParameterForm.get('type').value;
if(type==="NUM"){
this.initNUMControlsForm();
}
else if(type ==="STRUCT"){
this.initStructControlsForm();
}
else{
this.initControlsForm();
}
}
How can I avoid this problem?
usually you need to create another instance of your object at beginning and modify that object by your form. You can create the new object by const newObj = {...originalObj} or const newObj = JSON.parse(JSON.stringify(originalObj))
if user tries to save, pass the new object to save function and after success save, copy it back to original object
if user cancels, do nothing because your original object is not changed

Custom Directive for Required/ngRequired

I want to validate a dropdown with required. Default required only works if value is null or blank (correct me if I'm wrong). I want required to give error and make form invalid true if value is 'not assigned'.
<select name="first" class="select" title="Select Approver" ng-model="applications.first" ng-options="x.id as x.value for x in list1" ng-change="SetToAll(applications.first,'1')" required></select>
Using this I can show error message but this does make form invalid
<span class="error" ng-show="applications.first == 'not assigned'?true:false">Select Approver</span>
SOLUTION:-
1) If you want to use required then Check Shannon Hochkins solution.
<form name="formName">
<select name="first" class="select" title="Select Approver" ng-model="applications.first" ng-options="x.id as x.value for x in list1" ng-change="SetToAll(applications.first,'1')" required="true">
<option value="">Not Assigned</option>
</select>
<span class="error" ng-show="formName.first.$invalid ?true:false">Select Approver</span>
<pre>{{formName | json}}</pre>
</form>
He Added a option with blank value <option value="">Not Assigned</option>. and set required="true" in select. This works perfectly.
2) Using custom directive.
app.directive('req', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.req;
var invalid = $attrs.invalid;
if (viewValue == invalid) {
// It's valid because we have nothing to compare against
ctrl.$setValidity('req', false);
} else {
ctrl.$setValidity('req', true);
}
};
$attrs.$observe('req', function(comparisonModel) {
// Whenever the comparison model changes we'll re-validate
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
]);
And Your html code :
<select invalid="not assigned" req={{applications.first}} name="first" class="select" ng-model="applications.first" ng-options="x.id as x.value for x in list1" title="Select Approver" ></select>
<span class="error" ng-show="Step5.first.$error.req">Select Approver</span>
Here you will have to set invalid="not assigned" or any value like invalid='0' or invalid=' '. In directive it compares with invalid attribute if value matches it will show error.
Add the required value to the select element, then you can use the FORM object to check if the field is valid or not.
You can also use the forms name, to access fields in the form to check validity.
If you want to add a 'default' option, to the dropdown, you can add in an option with an empty value which is technically invalid on a required dropdown menu. You can choose to hide it if it is valid so the user can't pick it again after a correct option has been chosen.
<form name="formName" ng-controller="testCtrl">
<select name="first" ng-options="x.id as x.value for x in list1" ng-model="applications.first" required>
<option value="" ng-hide="formName.first.$valid">Not Assigned</option>
</select>
<pre>{{formName.first.$invalid | json}}</pre>
</form>
Inside your controller, setup some options:
angular.module('sandbox', []).controller('testCtrl', function($scope) {
$scope.list1 = [{
id: 1,
value: 'apples'
}, {
id: 2,
value: 'oranges'
}];
});
Demo: https://jsfiddle.net/suunyz3e/304/

Autocomplete with datalist [duplicate]

Currently the HTML5 <datalist> element is supported in most major browsers (except Safari) and seems like an interesting way to add suggestions to an input.
However, there seem to be some discrepancies between the implementation of the value attribute and the inner text on the <option>. For example:
<input list="answers" name="answer">
<datalist id="answers">
<option value="42">The answer</option>
</datalist>
This is handled differently by different browsers:
Chrome and Opera:
FireFox and IE 11:
After selecting one, the input is filled with the value and not the inner text. I only want the user to see the text ("The answer") in the dropdown and in the input, but pass the value 42 on submit, like a select would.
How can I make all browsers have the dropdown list show the labels (inner text) of the <option>s, but send the value attribute when the form is submitted?
Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.
Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.
If you want to disallow user input entirely, maybe select would be a better choice.
To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:
To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.
<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.
Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""
Working jsFiddle examples: plain javascript and jQuery
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).
So I modified Stephan Muller's answer slightly:
A datalist with non-unique values:
<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
<option value="42">The answer</option>
<option value="43">The answer</option>
<option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
When the user selects an option, the browser replaces input.value with the value of the datalist option instead of the innerText.
The following code then checks for an option with that value, pushes that into the hidden field and replaces the input.value with the innerText.
document.querySelector('#answerInput').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');
if (options.length > 0) {
hiddenInput.value = input.value;
input.value = options[0].innerText;
}
});
As a consequence the user sees whatever the option's innerText says, but the unique id from option.value is available upon form submit.
Demo jsFiddle
When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id) and search for it specific.
$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+
$('#autocomplete_input').val() +'"]').data('value'));
})
to get text() instead of val() try:
$("#datalistid option[value='" + $('#inputid').val() + "']").text();
Using PHP i've found a quite simple way to do this. Guys, Just Use something like this
<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
<datalist id="customers">
<?php
$querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
$resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());
while ($row_this = mysqli_fetch_array($resultSnamex)) {
echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
<input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
}
?>
</datalist>
The Code Above lets the form carry the id of the option also selected.

Not send GET variable on submit if dropwdown not selected

I have a form that I used to filter search results that consist of only dropdowns. I use GET rather then post so that the results can easily be shared with the URL.
<form action="" name='filter' method="GET">
<select name="Make" id="Make">
<option selected="selected" value ="nothing">All</option>
<option value="Toyota">Toyota</option>
<option value="Honda">Honda</option>
</select>
<input type="submit" value="Filter">
</form>
As it is right now if It will submit the value "nothing" for the get variable Make if the user doesn't change the selection. They're are multiple drop downs identical as this one for model year etc.
Is it possible for the Make variable to not show up in the URL if it isn't used?
As it is now if that code is submited it will say website.com/?Make=nothing. I tried removing the value and then it says website.com/?Make=All. I do not want make to show up in the URL if "All" is selected. Is this possible?
You don't have a submit button :)
you can add a JS that runs on submit and checks the value of "Make" and in case it's "nothing" just do a simple redirect instead of submitting the form. Something like:
var e = document.getElementById("Make");
var val = e.options[e.selectedIndex].value;
if (val === 'nothing'){
window.location = "http://www.google.com/"
}