Viewed   56 times

Question: i have country dropdown list and region dropdown list. Region drop downlist should be populated with values based on the chosen country using jQuery. I googled and tried to solve this problem, but i failed, i couldn't do it. Any simple steps that would help me achieve this?

Here is my snippet:

Basically first page load will populate the drodown lists from db and also store the list in sessions so list can re-used at application level as long as the session is active.

Default countryID and regionID are put in session called $_SESSION['regionID'] and $_SESSION['countryID']

    if(!isset($_SESSION['countryList']))
    {
        $_SESSION['countryList'] = array();
    }

    if(!isset($_SESSION['regionList']))
    {
        $_SESSION['regionList'] = array();
    }

.
.
.
        <form action="index.php" method="GET">
            <label for="lbl_country" id="countrylabel">Country</label>
            <select name="country" id="countrylist" onchange="getRegions(<?php $_SESSION['regionID']; ?>)">
                 <?php
                    //fetch country list from database and store it in session      
                    if(isset($_SESSION['countryList']) && !empty($_SESSION['countryList']))
                    {
                        foreach ($_SESSION['countryList'] as $val)
                        {
                            echo '<option value="'.$val['countryID'].'"';
                            if($_SESSION['countryID'] == $val['countryID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$val['countryName']."</option>'";
                        }   
                    }
                    else //means the session is not set yet-or-session is empty. Either case, we have to fetch
                    {
                        $query = "SELECT countryID, countryName FROM Country ORDER BY countryID ASC";
                        $results = mysql_query($query);
                        while ($row = mysql_fetch_assoc($results)) 
                        {
                            echo '<option value="'.$row['countryID'].'"';
                            if($_SESSION['countryID'] == $row['countryID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$row['countryName']."</option>'";

                            $_SESSION['countryList'][] = $row;
                        }   
                    }                   
                ?>
            </select>

            <label for="lbl_region" id="regionlabel">Region</label>
            <select name="region" id="regionlist">
                  <?php     
                    if(isset($_SESSION['regionList']) && !empty($_SESSION['regionList']))
                    {
                        foreach ($_SESSION['regionList'] as $val)
                        {
                            echo '<option value="'.$val['regionID'].'"';
                            if($_SESSION['regionID'] == $val['regionID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$val['regionName']."</option>'";
                        }   
                    }
                    else
                    {
                        $query = "SELECT regionID, countryID, regionName FROM Region WHERE countryID =".$_SESSION['countryID']." ORDER BY regionID ASC";
                        $results = mysql_query($query);
                        while ($row = mysql_fetch_assoc($results)) 
                        {
                            echo '<option value="'.$row['regionID'].'"';
                            if($_SESSION['regionID'] == $row['regionID'])
                            {
                                echo 'selected';    
                            }
                            echo ">".$row['regionName']."</option>'";

                            //everytime you go to a loop, make sure to put the result in the session
                            $_SESSION['regionList'][] = $row;
                        }   
                    }
                ?>
            </select>
</form>

 Answers

1

Lets take an easy example, I'm using this and it works perfectly fine.

This is the country dropdown:

<?php
        $countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
        echo "<select name='country' id='country' onchange="reload(this.form)" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
        while($clist=mysql_fetch_array($countrylist))
        {
        echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
        }
        echo "</select>";
 ?>

This is the region dropdown:

<select name="region" id="region" ></select>

Now make a seperate file named crlist.js and include it in the page having above code like this:

<script  type="text/javascript" src="crlist.js"> </script>

code for crlist.js:

var request = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
@end @*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}

function go() {
if (request.readyState == 4) {
//if (request.status == 200) {

var response = request.responseText;

var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
                list.remove(i);
            }
var records=response.split('|');
for (i=1; i<records.length; i++) {
    //alert("rcord="+records[i]);
    var record=records[i].split('*');
    var region=record[0];
    //alert("region="+region);
    var regionid=record[1];
    //alert("regionid="+regionid);
    var x=document.createElement('option');
    //var y=document.createTextNode(region);
    x.text=region;
    //x.value=region;
    //alert(x.text);
   //x.appendChild(y);
   //list.appendChild(x);
   list.options.add(x);
   }
  //}
 }
}

function initCs(path) {

if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
    country.onchange=function() {

        if(this.value!="Select") {

            var list=document.getElementById("region");
            for (i = list.length - 1; i>=0; i--) {
                list.remove(i);
            }
        //while (list.childNodes[0]) {
        //list.removeChild(list.childNodes[0]);
        //}
        }
        fillSelect(this.value,path);
        //alert(this.value);

    }
//fillSelect(country.value);
}

Now make a seperate file named crlist.php.

Code for crlist.php:

<?php
require_once 'yourconfigfile.php';

$cname = $_GET['country'];

$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
    echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}       
?>

Now add following script on the page having dropdowns:

<script  type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {

    initCs("");

});
</script>

This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.

Hope this helps.

Monday, December 26, 2022
2

*Updated to include all of the fields you are editing

It sounds like you have the right idea. You would probably want to create a new div on your page for the edit modal dialog.

<div id="dialog-edit" style="background-color:#CCC;display:none;">
    <input type="hidden" id="editLinkId" value="" />
    Link Name: <input type="text" id="txtLinkTitle" class="text" />
    Link Description <input type="text" id="txtLinkDescription" class="text" />
    Link URL <input type="text" id="txtLinkURL" class="text" />
</div>

When the user clicks your edit button you'll want to populate the hidden field and the text box with the values of the link they clicked on and then turn the dialog on.

$('.edit').click(function () {
            //populate the fields in the edit dialog. 
            var parent = $(this).closest('div');
            var id = parent.attr('id');

            $("#editLinkId").val(id);

            //get the title field
            var title = $(parent).find('.linkHeader').html();
            var description = $(parent).find('.linkDescription p').html();
            var url = $(parent).find('.linkDescription span a').attr("href");
            $("#txtLinkTitle").val(title);
            $("#txtLinkDescription").val(description);
            $("#txtLinkURL").val(url);

            $("#dialog-edit").dialog({
                bgiframe: true,
                autoOpen: false,
                width: 400,
                height: 400,
                modal: true,
                title: 'Update Link',
                buttons: {
                    'Update link': function () {
                        //code to update link goes here...most likely an ajax call.

                        var linkID = $("#linkID").val();
                        var linkTitle = $("#txtLinkTitle").val()
                        var linkDescription = $("#txtLinkDescription").val()
                        var linkURL = $("#txtLinkURL").val()
                        $.ajax({
                            type: "GET",
                            url: "ajax_calls.php?function=updateLink&linkID=" + linkID + "&linkTitle=" + linkTitle + "&linkDescription=" + linkDescription + "&linkURL=" + linkURL,
                            dataType: "text",
                            error: function (request, status, error) {
                                alert("An error occured while trying to complete your request: " + error);
                            },
                            success: function (msg) {
                                //success, do something 
                            },
                            complete: function () {
                                //do whatever you want 
                            }
                        }); //end ajax
                        //close dialog
                        $(this).dialog('close');
                    },
                    Cancel: function () {
                        $(this).dialog('close');
                    }
                },
                close: function () {
                    $(this).dialog("destroy");
                }
            }); //end .dialog()

            $("#dialog-edit").show();
            $("#dialog-edit").dialog("open");

        }) //end edit click
Thursday, August 11, 2022
 
3

If you have a select element that looks like this:

<select id="ddlViewBy">
  <option value="1">test1</option>
  <option value="2" selected="selected">test2</option>
  <option value="3">test3</option>
</select>

Running this code:

var e = document.getElementById("ddlViewBy");
var strUser = e.value;

Would make strUser be 2. If what you actually want is test2, then do this:

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;

Which would make strUser be test2

Monday, August 1, 2022
 
jhn
 
jhn
4

This will help:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

url='' //of webpage

driver.maximize_window()

driver.get(url)

listofelements=driver.find_elements(By.XPATH,'//*[@name="fromMonth"]/option') //to take all elements matching xpath

for i in range(len(listofelements)):
    print(listofelements[i].text) //print all elements of list
Friday, November 18, 2022
3

i think your problem may be in ajax code since you are using formData object . try append the message variable with it

$('#submit').on('click', function(){

  var fd = new FormData(this);
  fd.append('file',$('#file')[0].files[0]);
  fd.append('message ',$('#message').val());

  $.ajax({
    method:"POST",
    url:"<?php echo site_url('home/send_chat');?>",    
    data: fd,  
    cache: false,
    contentType: false,
    processData: false,   
    success: function(data){                 
      alert(data);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }  
  });
});
Saturday, November 12, 2022
 
malina
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :