当field1在表单中更改时更改field2

时间:2014-09-17 09:22:52

标签: javascript php jquery forms

我有一个表单,它要求field1一个序列号。然后在第二个字段中,它将询问模型。但我可以找到带序列号的型号。它的3&串口的第4个数字。因此,我没有询问型号,而是想在没有用户干预的情况下直接放置模型。

我希望在更新field1时直接更改field2,而不是在表单发布后更改。

首先,是否只能使用php?我在jQuery,Ajax和JS方面的知识非常有限。

以下是我现在的表现:

        <div class="col-xs-6">
            <div class="form-group">
            <label for="no_serie_produit" class="label col-xs-3">N° Série Produit</label>
                <div class="col-xs-10">
                    <input type="text"  name="no_serie_produit" id="no_serie_produit" placeholder="N° Série de ... (Obligatoire) ">
                </div>
            </div>
            <div class="form-group">
                <label for="model_produit" class="label col-xs-3">Modele Produit</label>
                    <div class="col-xs-10">
                        <input type="text"  name="model_produit" id="model_produit" placeholder="Modèle ... (Obligatoire)">
                    </div>
            </div>
        </div>

第二:如果我真的需要使用像JS或jQuery这样的东西,你能否建议我最容易学习。

修改

示例:

如果我输入Serial n°:14020001,我想在field2:TMSA4-NET LV

1 个答案:

答案 0 :(得分:2)

#no_serie_produit上收听input事件,然后相应地设置#model_produit的值:

$('#no_serie_produit').on('input', function() {
    // don't do anything before 4 digits are inputted
    if (this.value.length < 4) return;

    // .slice()'s start is inclusive, end is exclusive
    var modelId = this.value.slice(3, 5);

    // do the Ajax call with $.ajax or the shorthand $.post/$.get methods
    $.get('path/to/getModelName.php', { modelId: modelId }, function(modelName) {
        // received the model name in the Ajax response, update the field
        $('#model_produit').val(modelName);
    });
});

这会向path/to/getModelName.php发送一个Ajax请求(相应地更新路径/文件名),在这个PHP文件中,您将能够通过$_GET['modelId']访问模型ID。然后,您可以使用它查询数据库并echo名称。回显的值将作为Ajax调用的响应返回,即在这种情况下$.get的回调的modelName参数。

一些阅读参考: