jQuery-选择后更改选项值 [英] Jquery - Change Option Value After Selection

查看:113
本文介绍了jQuery-选择后更改选项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jquery Ajax从选定的checkbox中显示不同的<option> 文本 value .在我的表单上,我有两个复选框供用户选择价格范围.下面的示例,

How to display different <option> text and value from a chosen checkbox using jquery Ajax. On my form, I have a two checkbox for user to choose price range. Example as below,

<input type="checkbox" name="price_range" value="1" id="ceo"> < RM 10,000 
<input type="checkbox" name="price_range" value="2" id="bod"> < RM 200,000

如果用户选择value='1'value='2',则两个选择选项值的输出将根据所选复选框而更改.

If user choose value='1' or value='2', the output of two select option value will change base on the selected checkbox.

//display application name
<select name="submited_by" id="submited_by">
  <option value="0">Choose Price Range</option>
</select>

//display name to approve application
<select name="hod" id="hod">
  <option value="0">Choose Price Range</option>
</select>

使用Ajax执行更改

$("input[name='price_range']").click(function() {
    var price = $(this).val();

    $.ajax({
        type: 'POST',
        url: 'DropdownValuesForm.php',
        data: { price : price }, 
        success: function(data){
            $('#submited_by').html(data)
        }
    }); 

});

DropdownValuesForm.php

<?php
require 'db_connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $price = $_POST['price'];
}

if($price == '< RM 10,000'){ 
    //do the Query

    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_assoc($result)){
            $submited_by = $row['staff_id'];    
            $nama = $row['nama'];

            echo '<option value=" ' . $submited_by . ' ">' . $nama . '</option>';
        }   
    } 
    mysqli_free_result($result);

} else {
    //do the Query

    if(mysqli_num_rows($result) > 0){
        while($row=mysqli_fetch_assoc($result)){
            $submited_id = $row['staff_id'];
            $nama_pemohon = $row['nama'];

            echo '<option value=" ' . $submited_id . ' ">' . $nama_pemohon . '</option>';
        }   
    } 
    mysqli_free_result($result);
}
?>

就我而言,它将仅针对<select name="submited_by">进行更改.我是否需要为<select name="hod" id="hod">创建另一个ajax函数,并创建另一个页面以从数据库获取DropdownValuesForm.php这样的值.

On my case, it will change for <select name="submited_by"> only. Do I need to make another ajax function for the <select name="hod" id="hod"> and make another page to get the value from database like DropdownValuesForm.php.

推荐答案

要做您想做的事情,您实际上只需要坚持用一个可以分发指令的ajax页面即可.查看我的答案(编辑/仅作为副言下的下半部分)

To do what you are trying to do, you really just need to stick with one ajax page that will dispatch instructions. See my answer (second half under EDIT/JUST AS A SIDE) here to see how to implement a simple dispatcher. Using the dispatcher from that post, here is what this workflow would look like:

表单复选框:

<!-- Unless you need the form to submit a 1 or 2, it would be better to send 10,000 or 20,000 instead of 1 or 2 -->
<input type="checkbox" name="price_range" value="1" id="ceo" data-instructions='{"action":"get_price_range","value":"< RM 10,000","sendto":"#submited_by"}' class="ajax_trigger" />
<input type="checkbox" name="price_range" value="2" id="bod" data-instructions='{"action":"get_price_range","value":"< RM 20,000","sendto":"#hod"}' class="ajax_trigger" />

jQuery:

$(document).ready(function() {
    var doc = $(this);
    // Create ajax instance (from other post, see that script)
    var Ajax = new AjaxEngine($);
    // If you trigger on a class, you can do ajax anywhere on your page
    doc.on('click', '.ajax_trigger', function() {
        // You will likely want to check first that the click is enabling
        // the checkbox or disabling it (check/uncheck) before you run the ajax
        // Extract the instructions
        var dataInstr = $(this).data('instructions');
        // Send the instructions
        Ajax.send(dataInstr,function(response) {
            // Use the extracted sendto to save to a spot on this page
            // It would be better to return json string to decode. This way
            // you can return instructions along with the html for further
            // dynamic processing...but this instance, this should do
            $(dataInstr.sendto).html(response);
        });
    });
});

$ _ POST:

您的帖子随后将发送:

Array(
    [action] => get_price_range
    [value] => < RM 10,000
    [sendto] => #submited_by
)

XML:

使用另一篇文章作为指导,您可以创建一个xml,将您的派遣指向该地点:

Using the other post as a guide, you can create an xml to point your dispatch to that spot:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <ajax>
        <action>
            <get_price_range>
                <include>/actions/get_price_range.php</include>
            </get_price_range>
        </action>
    </ajax>
</config>

您的调度将把此页面包括在呼叫中:

Your dispatch would then include this page into the call:

/actions/get_price_range.php

/functions/getPriceOptions.php

将关键脚本放入函数(类/方法以获得更大的灵活性)中,以实现可移植性和重用性.

Put key scripts into functions (class/methods for even more flexibility) for portability and re-use.

<?php
/*
** @description  This will return your options
** @param $key [string] This is whatever you used to isolate the data in your sql call
** @param $db [resource] This is the mysqli connection that you need to run the query
*/
function getPriceOptions($key,$db)
    {
        ##################
        ## do the query ##
        ##################

        if(mysqli_num_rows($result) > 0){
            while($row = mysqli_fetch_assoc($result)){
                $submited_by = $row['staff_id'];    
                $nama        = $row['nama'];
                # You may want to just return data and not a view
                # the function will be more flexible that way
                $disp[]      = '<option value=" ' . $submited_by . ' ">' . $nama . '</option>';
            }
        }
        mysqli_free_result($result);
        return (!empty($disp))? implode(PHP_EOL,$disp):'';
    }

/actions/get_price_range.php

<?php
require_once(__DIR__.'/db_connection.php');
# include the function
require_once(__DIR__.'/functions/getPriceOptions.php');
# Isolate the post
$price = $_POST['price'];
# Get the query key word/value to search your database
$key   = ($price == '< RM 10,000')? 'whatever' : 'otherwhatever';
# Write to the view
echo getPriceOptions($key,$db);

演示:

这里是链接文章及以上内容中所有集成脚本的演示.该示例略有不同,因为我没有您的表,并且想发回post数组,以便您也可以看到它,但是最终结果是相同的:

Here is a demo of all the integrating script from the linked post and the above. The example is slightly different because I don't have your table and I want to send back the post array so you can see that as well, but the end result is the same:

http://www.nubersoft.com/tester.php?example=39736539

这篇关于jQuery-选择后更改选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆