How to get value of data-flag - javascript

Community, I have a select drop down which is trying to pass two variables to javascript. The first variable is (source_id) and the second is (source_flag).
My select looks like the following...
<select id="ticket_source" name="ticket_source" onchange="showEmail(this)">
<option value="">Select Source</option>
I use query to populate remaining options.
$get_sources = mysql_query("select source_id, source_name, source_flag from ticket_source order by source_name ASC");
while(($source_list = mysql_fetch_assoc($get_sources)))
{
echo '<option value="'.$source_list['source_id'].'" data-flag="'.$source_list['source_flag'].'">'.$source_list['source_name'].'</option>
}
<option value="0">Other</option>
</select>';
My javascript will make a hidden div appear. I'm trying to obtain the value stored in the data-flag attribute, and I'm not quite sure if there is a certain route to do that.
function showEmail(element)
{
var id = element.value;
var divTwo = document.getElementById("ticket_source");
var flag = divTwo.getAttribute('data-flag');
alert(flag);
// Do something with flag...
var div = document.getElementById("received");
if(id == 2 || id == 3 || id == 5)
{
div.style.display = 'block';
}
else
{
div.style.display = 'none';
}
}

How about this in pure javascript
var flag =document.getElementById('ticket_source').options[select.selectedIndex].data-flag;
or
var flag =element.options[element.selectedIndex].data-flag;
var flag =element.options[element.selectedIndex].getAttribute('data-flag');
See Fiddle Here

Try this:
var flag = document.querySelector('#ticket_source').dataset.flag; // using javascript
var flag = $('#ticket_source').data('flag'); // using jquery
JSBIN Link: http://jsbin.com/ujiday/228/

In modern browsers you could do this
document.getElementById('myThing').dataset.flag
However, that won't work in non-HTML5 compliant browsers, so you'd want to use getAttribute like you've done in your code above.
Alternatively if you're using jQuery, Mohit Pandey's answer would be good.
Edit: Looking at your code, it also looks like you're trying to pull the data value from the select box, while in your PHP you're adding it to the options, which would explain why it was returning null/undefined.
Made a fiddle (using jQuery)
http://jsfiddle.net/QAsgN/

Related

Why auto complete does not work in this example with Bootstrap?

I am trying to implement an auto complete dropdown with dynamic data but it doesnt display any suggestions in the dropdown. I am using this example - Datalists: https://getbootstrap.com/docs/5.1/forms/form-control/
which works fine with predefined option tags.
<label for="exampleDataList" class="form-label">Datalist example</label>
<input class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
<datalist id="datalistOptions">
... dynamic data here
</datalist>
I do receive data from the PHP script and they are correctly accessed but I think the problem might be due to the delay of the fetch. HTML might expect the data to already be there when loaded. That's why maybe it works with existing data.
here is the javacsript code inside the fetch function where I dynamically produce the tags:
var select = document.getElementById("datalistOptions");
select.innerHTML = "";
for (var key in data['result']) {
var val = data['result'][key];
if (data['result'].hasOwnProperty(key) && key != "error") {
var val = data['result'][key];
if (val != "") {
var option = document.createElement("option");
option.value = val.id;
select.appendChild(option);
}
}
}
Update: I changed the js code a bit. Now it uses appendChild instead of add function. The previous one was not adding any options to the datalist. appendChild does add options to the list but it does not display them.
This is a simpler version of what you trying to do.
Try to take it, add your conditions, and make that data come in that form if you can.
var data = ["Haifa","Tel Aviv","Jerusalem"];
var select = document.getElementById("datalistOptions");
select.innerHTML = "";
for (var key in data) {
var option = document.createElement("option");
option.label = data[key];
option.value = data[key];
select.appendChild(option);
}
And make sure you adds onclick event that calls you script, maybe this is you problem, that you not calling the script - I would recomand somethig like that:
<input onclick="datalistCreate()" class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
datalistCreate() is the function name in the script.

Set PHP array to work with dropdown list created from Json object

I have been stuck on this for a few days now and could use some expert advice!
So, as a personal/learning project I'm making a fun little 'character relationship tracker' for my friends' D&D games. With this, I have a DB table of dummy dungeon masters as well as the game(s) they are running for the purpose of testing code. I am trying to create a cascading dropdown list generated from a mix of PHP and encoded to JSON as part of the submit new character form. It works! Except, in the database containing the info for the options, some have only one game in the list for a DM while others have multiple games for the same DM. For those singles, the JS is listing out every single letter as a different choice instead of just the single full option. I have tried remaking the PHP twice to try resolving this and shuffled through a handful of JS attempts to no avail. These changes have either broken the code completely or resulted in no changes.
This fiddle is what it is doing with my best attempt
as for the actual code:
HTML
<div class="selectdiv">
<select name="chargm" id="charadm" onChange="chgm(this.value);" required>
<option value="" selected="true" disabled>Game Master</option>
<?php foreach ($gameMasters as $masterName) { echo "<option value='". $masterName . "'>" . $masterName . "</option>"; } ?>
</select>
</div>
<div class="selectdiv">
<select name="chargame" id="chargm" required>
<option value="" selected="true" disabled>Game Name</option>
</select>
</div>
here is the PHP (I know it's super messy and redundant but I couldn't get it to work any other way for some reason and it does its job?)
//database connection stuff
$sqls = "SELECT * FROM datgames;";
$stmts = mysqli_query($conn, $sqls);
$resultcheck = mysqli_num_rows($stmts);
$gameMasters = array(); //create empty array of game masters.
$gameData = array(); //set up game list data array
//check if db can be read before contiuning.
if($resultcheck > 0){
while($row = mysqli_fetch_assoc($stmts)){ //while there are rows, add to array
$gameMasters[] = $row["datgamDM"]; //fill the gameMasters array with all gm's
$gmdm = $row["datgamDM"]; //define gmdm as the game master of the row
//copy existing info in gameData to preserve data
$anotm = $gameData;
//clear game data to reset it to avoid repeats
unset($gameData);
//create the key => value pair
$tmpar[$gmdm] = $row["datgamName"];
//merge the temp arrays and apply them to the global array
$gameData = array_merge_recursive($anotm, $tmpar);
//clear the temporary arrays to avoid repeats
unset($anotm);
unset($tmpar);
}
}else{ exit(); } //if db can't be reached, break the code.
$gameMasters = array_unique($gameMasters);
//print_r($gameData); //making sure the array is right. this line is removed once this is working
and the exact JSON output from the PHP currently with this loop
{
"Reid":[
"Curse of Strahd",
"ufkck"],
"bob":[
"Curse of Strahd",
"fffs"]
,"jomama":"blaal",
"taco":"salff"
};
and the JS adapted from divy3993's answer here
var list = <?php echo json_encode($gameData); ?>;
function chgm(value) {
if (value.length == 0) document.getElementById("chargm").innerHTML = "<option></option>";
else {
var games = "";
for (categoryId in list[value]) {
games += "<option>" + list[value][categoryId] + "</option>";
}
document.getElementById("chargm").innerHTML = games;
}
}
The question in short: What am I doing wrong in either PHP (most likely the cause) or Javascript that is causing the words in single-object groups to split into letters instead of showing the full word as the only option for the second drop down option?
Or rather, how do I get the PHP to make single-entries to show up as a multidimensional array while keeping the key so it shows up as an array in the JSON object?
The trouble with using array_merge_recursive() is that it can produce an inconsistent structure as it creates depth.
For instance, see that a 1st level key contains an indexed subarray if there is more than one element, but creates an associative array on the first level when only one element exists. I explain this here and provide a simple demonstration.
A result set from mysqli's query() is instantly traversable using foreach(), so I recommend that concise technique which sets up intuitive associative array accessing.
$result = [];
foreach ($conn->query("SELECT datgamDM, datgamName FROM datgames") as $row) {
$result[$row["datgamDM"]][] = $row["datgamName"];
}
exit(json_encode($result));
This way, you have a consistent structure -- an associative array of indexed arrays. In other words:
{
"Reid":["Curse of Strahd","ufkck"],
"bob":["Curse of Strahd","fffs"],
"jomama":["blaal"],
"taco":["salff"]
}
Then life only gets easier. You only need to iterate like:
for (index in list[value]) {
As for the technique that you are using to generate the select/option markup -- that's not the way I would do it, there are multiple ways to do it, there are TONS of pages on StackOverflow that explain these options for you.
I generally don't like the UI of providing form instructions or labels as the top option of a field. I recommend that you give your form fields <label>s so that the options only contain real options.
As a completely different alternative, if you don't want to keep modifying the DOM every time the user makes a selection change, you could print ALL of the secondary select fields with their options preloaded, then "hide" them all. Then as the user changes the primary select field, merely "show" the field with the related id. This does of course create more html markup (which may or may not be attractive depending on your data volume), but it greatly reduces the complexity of the javascript code since all of the dynamic processing is done on page load. If one day, you wanted to make your primary select field a "multi-select", then having toggle-able secondary fields will work nicely. ..."horses for courses" and all that.
don't take my comments too serious
// is your old code
/// are my comments
var list = {
"Reid": ["Curse of Strahd", "uuck"],
"bob": ["Curse of Strahd", "fffts"],
"jomama": "blaal",
"taco": "salff"
};
function chgm(value) {
// if (value.length == 0) document.getElementById("chargm").innerHTML = "<option></option>";
/// do not use == use ===
/// avoid innerHTML
var node = document.getElementById("chargm");
var option;
if (!value) {
node.appendChild( document.createElement('options') );
return;
}
//else {
/// pls do not append to a string!
/// imagine you have 7000 values, the OS have everytime to get the string size AND
/// (re-)allocate new memory!!
// var games = "";
/// var games = []; // use an array instead of!
/// use of instead of in, if you want to use in, you have to make sure if list.hasOwnProperty(value) is true
// for (gameMas in list[value]) {
/// for (var gameMas of Object.keys(list)) {
/// but we know already what we are looking for, so let's check for that:
if (list.hasOwnProperty(value)) {
// ok we have now other new values, but what's with the other ones?
// lets kill everything for lazyness
while(node.firstChild && node.removeChild(node.firstChild));
/// reset the header
node.appendChild( document.createElement('option') ).innerText = 'Game / RP Name';
// games += "<option>" + list[value][gameMas] + "</option>";
/// your example array is inconsistent, so we have to check for the type
if (!Array.isArray(list[value])) {
/// with an array do this:
/// games.push('<option>' + list[gameMas] + '</option>');
option = node.appendChild( document.createElement('option') );
option.innerText = list[value];
option.value = list[value];
return;
}
/// else
for (var v of list[value]) {
/// with an array do this:
/// games.push('<option>' + list[gameMas][value] + '</option>');
option = node.appendChild( document.createElement('option') );
option.innerText = v;
option.value = v;
}
}
// document.getElementById("chargm").innerHTML = games;
/// with an array do this:
/// document.getElementById("chargm").innerHTML = games.join('');
}
<select name="chargm" id="charadm" onChange="chgm(this.value);">
<option value="" selected="true" disabled="">DM/Admin</option>
<option value="Reid">Reid</option>
<option value="bob">bob</option>
<option value="jomama">jomama</option>
<option value="taco">taco</option>
</select>
<select name="chargame" id="chargm">
<option value="" selected="true" disabled>Game / RP Name</option>
</select>

How do you return data from javascript into a html form?

I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable

How to populate a dropdown list based on values of the another list?

I want to implement a search box same as this, at first, just first dropdown list is active once user selects an option from the first dropbox, the second dropdown box will be activated and its list will be populated.
<s:select id="country" name="country" label="Country" list="%{country} onchange="findCities(this.value)"/>
<s:select id="city" name="city" label="Location" list=""/>
Jquery chained plugin will serve your purpose,
https://plugins.jquery.com/chained/
usage link - http://www.appelsiini.net/projects/chained
this plugin will chain your textboxes.
Try this code where based on your needs you have to populate it with your options:
var x;
$('#pu-country').on('change', function () {
if (this.value != '0') {
$('#pu-city').prop('disabled', false);
$('#pu-city').find("option").not(":first").remove();
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
switch (this.value) {
case 'A':
x = '<option value="A.1">A.1</option><option value="A.2">A.2</option><option value="A.3">A.3</option>'
}
$('#pu-city').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
$('#pu-city').prop('disabled', true);
$('#pu-city').val("Choose");
}
});
$('#pu-city').on('change', function () {
if (this.value != '0') {
$('#pu-location').prop('disabled', false);
$('#pu-location').find("option").not(":first").remove();
switch (this.value) {
case 'A.1':
x = '<option value="A.1.1">A.1.1</option><option value="A.1.2">A.1.2</option><option value="A.1.3">A.1.3</option>'
break;
case 'A.2':
x = '<option value="A.2.1">A.2.1</option><option value="A.2.2">A.2.2</option><option value="A.2.3">A.2.3</option>'
break;
case 'A.3':
x = '<option value="A.3.1">A.3.1</option><option value="A.3.2">A.3.2</option><option value="A.3.3">A.3.3</option>'
break;
}
$('#pu-location').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
}
});
I have also set up and a demo to see the functionallity with more options.
FIDDLE
Your code should be something like this:
$(country).change(function(){
var l=Document.getElementByID("country");
for(i=0;i<=l.length;i++)
{
if(l.options[i].selected?)
{
text_array=[HERE YOU NEED TO ADD THE CITIES OF l.options[i].text];
val_array=[HERE YOU NEED TO ADD THE VALUES OF THECITIES OF l.options[i].text];
}
}
var c=Document.getElementByID("city");
c.options.text=[];
c.options.value=[];
//You now should have an empty select.
c.options.text=text_array ;
c.options.value=val_array ;
});
As I don't know, what kind of DB you use, to have the cities connected to their countrys, I can't tell you, what to put into the uppercase text...
Ciao j888, in this fiddle i tried to reconstruct the same system as the site you provided the link
the number of states cityes and locality is less but the concept remains the same
If you want to add a new state you must enter a new html options in select#paese with an id.
Then you have add in obj.citta a property with this id name and an array of cityes for a value.
The same thing for obj.localita where you will create an array of arrays.
The jQuery code you need is
<script type="text/javascript">
$(document).ready(function(){
var obj={
citta:{ //value is the same of option id
albania:['Durres','Tirana'],
austria:['Vienna','innsbruck','Graz'],
},
localita:{//for every city create a sub array of places
albania:[['località Durres1','località Durres 2'],['località Tirana','località Tirana 2']],
austria:[['località Vienna','località Vienna 2'],['località innsbruck','località innsbruck 2'],['località Graz','località Graz 2','località Graz 3']],
}
}
$('#paese').on('change',function(){
$('#località').attr('disabled','disabled').find('option').remove()
var quale=$(this).find('option:selected').attr('id')
var arr=obj.citta[quale]
if(arr){
$('#citta').removeAttr('disabled')
$('#citta option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#citta')
}
}
})
$('#citta').on('change',function(){
var ind=($(this).find('option:selected').index())-1
var quale=$('#paese').find('option:selected').attr('id')
var arr=obj.localita[quale][ind]
if(arr){
$('#località').removeAttr('disabled')
$('#località option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#località')
}
}
})
})
</script>
If this solution does not suit your needs, i apologize for making you lose time.
Hi i have done this for license and its dependent subject in yii 1.
The license dropdown
//php code
foreach($subject as $v) {
$subj .= $v['licenseId'] . ":" . $v['subjectId'] . ":" . $v['displayName'] . ";";
}
Yii::app()->clientScript->registerScript('variables', 'var subj = "' . $subj . '";', CClientScript::POS_HEAD);
?>
//javascript code
jQuery(document).ready(function($) {
//subject. dependent dropdown list based on licnse
var ty, subjs = subj.split(';'), subjSel = []; //subj register this varible from php it is
for(var i=0; i<subjs.length -1; i++) { //-1 caters for the last ";"
ty = subjs[i].split(":");
subjSel[i] = {licId:ty[0], subjId:ty[1], subjName:ty[2]};
}
//dropdown license
jQuery('#license#').change(function() {
$('#add').html(''); //clear the radios if any
val = $('input[name="license"]:checked').val();
var selectVals = "";
selectVals += '<select>';
for(var i=0; i<subjSel.length; i++) {
if(subjSel[i].licId == val) {
if(subjSel[i].subjId *1 == 9) continue;
selectVals += '<option value="'+subjSel[i].subjId+'">'+subjSel[i].subjName+'</option>';
}
}
selectVals += '</select>';
$("#subject").html(selectVals);
});
});
You seem to be asking two questions:
QUESTION 1. How to have a disabled select box (the second and third select boxes in the case of your example) which is activated upon the selection of an option from the first select box.
ANSWER 1:
simply use the disabled=true/false as below...
<select id="country" name="country" label="Country" onchange="document.getElementById('city').disabled=false; findCities(this.value)"/>
<select id="city" name="city" label="Location" disabled=true/>
NOTE: I changed "s:select" to "select" on the basis that your question does not make reference or tag the Struts framework that uses this syntax.
QUESTION 2: How to populate the second select box when a selection is made in the first.
ANSWER 2: There are many ways to do this, and the choice depends on where you have the data to populate the lists with. In the case of your Rentalcars example, if you chose Barbados, the browser sends an ajax GET request to "http://www.rentalcars.com/AjaxDroplists.do;jsessionid=5DCBF81333A88F37BC7AE15D21E10C41.node012a?country=Barbados&wrapNonAirports=true" -try clicking on this link and you will see what that request is sending back. This '.do' address is a server side file of a type used with the Struts framework I mentioned above.
A more conventional approach, which would be included in your function findCities(country)would be to send an AJAX request to a PHP script which queries a database and sends back an array of place names to the browser. The AJAX javascript code includes instructions as to what to do with the response. Without knowing more about where you want to store your list, giving an example of this would most likely not be useful.
Alternatively, the whole list of places could be included in the javascript script as an array (as demonstarated by Devima, above), in a text document on the server as comma separated values, or you could save it to a browser database like WebSQL or IndexedDB if offline use would be useful.
When you have got your list, probably as an array of values, you could save the array as a variable eg. var cities=result (in the case of a simple ajax request). You will then need to iterate through cities, for example
for (var i = 0; i < cities.length; i++){
var place=cities[i];//an individual city name
document.getElementById("city").innerHTML+="<option value='" + place + "'>" + place + "</option>";//adds an 'option' with the value being the city name and the text you see being the city name
}
IMO this is the base case AngularJS was designed to completely alleviate. Check it out!

How to get the value of an option in a dropdown by knowing only the id of select tag using javascript

here is my js code:
var currentsecondarycategory = document.getElementById("se_category");
if(currentsecondarycategory.childElementCount > 1)
{
if(!currentsecondarycategory.value.match(whiteSpaceRegExp))
{
error = 1;
alert("please enter a secondary category for the Item.");
currentElement.select();
currentElement.focus();
return;
}
}
i want to check if their is only one option,then how to check the value of that option,so that if it is other than the value "No records found",then i can apply the 2nd if condition above to that option also.please help me.
here the options are coming dynamically,so not possible to check by a single id.
Use .value property of currentsecondarycategory. Here is a jsfiddle demonstrating the process:
http://jsfiddle.net/2nNy3/
HTML
<select id="dropdown"><option value="test">that's the value</option></select>
JS
console.log(document.getElementById("dropdown").value);
If you want to get the text of the option tag then use:
document.getElementById("dropdown").options[0].innerHTML;
Use currentsecondarycategory.childNodes to get the <option> nodes within the <select>. If there is only one option, it will be currentsecondarycategory.childNodes[0], and its value will be currentsecondarycategory.childNodes[0].value.
var currentsecondarycategory = document.getElementById("se_category");
if(currentsecondarycategory.selectedIndex == 0){
alert('put your message here');
return false;
}
currentsecondarycategory.selectedIndex it will return the selected index of the selectbox
please try this...may helpful

Categories

Resources