简体   繁体   English

在onClick事件之前设置输入值

[英]Set input value before onClick event

I have a Group of Radio button with different values, I'm trying to call a function based on the value of the input. 我有一组具有不同值的单选按钮,我正在尝试根据输入的值调用一个函数。

HTML: HTML:

<form class="form">
 <div class="btn-group btn-group-justified " data-toggle="buttons" name="chartSelect">
   <label class="btn btn-info"  onclick="getChart()">
     <input name="chart" value="" type="radio">All
   </label>
   <label class="btn btn-info" onclick="getChart()">
     <input name="chart" value="total" type="radio">Total
   </label>
   <label class="btn btn-info" onclick="getChart()">
     <input name="chart" value="max" type="radio">Max
   </label>
   <label class="btn btn-info" onclick="getChart()">
     <input name="chart" value="mean" type="radio">Mean
   </label>
   <label class="btn btn-info" onclick="getChart()">
     <input name="chart" value="min" type="radio">Min
   </label>
   <label class="btn btn-info" onclick="getChart()">
     <input name="chart" value="extrapolation" type="radio">Extrapolation
   </label>
 </div>
</form>

JS: JS:

function getChart() {
    var startDate = $('#range').val().slice(0, 10) + 'T' + $('#range').val().slice(11, 16) + ':00+00:00';
    var endDate = $('#range').val().slice(19, 29) + 'T' + $('#range').val().slice(30, 38) + ':00+00:00';
    var appName = $('select[name=applicationSelect]').val();
    var envName = $('input[name=env]:checked').val();
    var chartType = $('input[name=chart]:checked').val();
    // Load chart
    ajaxLoadChart(startDate, endDate, appName, envName, chartType);
};

// Function for loading data via AJAX and showing it on the chart
function ajaxLoadChart(startDate, endDate, appName, envName, chartType) {
    // If no data is passed (the chart was cleared)
    if (!startDate || !endDate) {
        return;
    }
    // Otherwise, issue an AJAX request
    $.ajax({
        url: 'http://MyServlet.com',
        crossDomain: true,
        async: true,
        type: "GET",
        dataType: "json",
        data: {
            start: startDate,
            end: endDate,
            env: envName,
            app: appName,
            type: chartType
        },
        success: function (data) {
            defaultChart(data);
        }
        error: function(xhr, status, error) {
        alert(status + " " + error);
        console.log(xhr);
        }
    });
}

The problem is value of the selected input is set after the function has been called so the previous selected value is fetched in the Ajax request. 问题是在调用函数后设置所选输入的值,以便在Ajax请求中获取先前的所选值。

I'm new to JS, can I fix this without massive changes to my code? 我是JS的新手,是否可以在不进行大量更改的情况下解决此问题?

set the parameter to the function 将参数设置为函数

function getChart(param){
alert(param);
}

and then give it to the event, 然后把它交给活动

<label class="btn btn-info" onclick="getChart(20)">
  <input name="chart" value="mean" type="radio">Mean
</label>
<label class="btn btn-info" onclick="getChart(25)">
  <input name="chart" value="mean" type="radio">Mean
</label>

It can be String value too, just give quote on the event 也可以是String值,只需在事件中提供引号

<label class="btn btn-info" onclick="getChart('mean')">
  <input name="chart" value="mean" type="radio">Mean
</label>

It will show the value of getChart into an alert. 它将在警报中显示getChart的值。 Sorry for bad english, I'm Erwin from Indonesia, hope this will help you :D 对不起,英语不好,我是印度尼西亚的Erwin,希望这对您有所帮助:D

This is because you have onClick handler on the label, and not the input field. 这是因为标签上有onClick处理程序,而不是输入字段。

Also it might be easier to extract values from input fields once any of them change using jQuery ala $('[type=input]').change(function(){ // extract all field values and call Ajax to retrieve new chart }); 同样,一旦使用jQuery ala $('[type = input]')。change(function(){//提取所有字段值并调用Ajax来检索新图表),则从输入字段中提取值可能会更容易。 );

Without significant changes to the existing code, you should simply let the event propagate before calling your getChart . 无需对现有代码进行重大更改,您只需在调用getChart之前让事件传播getChart Change the function name of getChart to getChart_ and create a new function like so: function getChart() { setTimeout(getChart_, 0); } getChart的函数名称更改为getChart_并创建一个新函数,如下所示: function getChart() { setTimeout(getChart_, 0); } function getChart() { setTimeout(getChart_, 0); } . function getChart() { setTimeout(getChart_, 0); }

What we're doing here is scheduling the original getChart call to happen after the event handler has been executed (and state of the input updated). 我们在这里要做的是安排原始的getChart调用在事件处理程序执行后(以及输入的状态已更新)发生。

As you have the code now, the function getChart will be executed twice on every click, because the event is fired for both the input element and the label element. 就像现在有了代码一样,每次单击都会对getChart函数执行两次,因为input元素和label元素都会触发该事件。 Which is the checked radio button at the time of these events is different for these two cases. 在这两种情况下,发生这些事件时选中的单选按钮是不同的。

But you'd anyway want to avoid a double call, as you'll want to do your Ajax calls only when necessary. 但是无论如何,您都希望避免重复调用,因为仅在必要时才需要进行Ajax调用。

I would advise to make these changes: 我建议进行以下更改:

  • First remove the onclick attributes from all input tags; 首先,从所有input代码中删除onclick属性;
  • Wrap the getChart function inside $('[name=chart]').change(...) . getChart函数包装在$('[name=chart]').change(...) This makes it the change event handler for all these chart input s in one go. 这使它成为所有这些图表input s的更改事件处理程序。

Here is the result (testable): 结果如下(可测试):

 $('[name=chart]').change(function getChart() { var chartType = $('input[name=chart]:checked').val(); // just for testing: alert('Choice = ' + chartType); // rest of your getChart function follows here... }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="form"> <div class="btn-group btn-group-justified " data-toggle="buttons" name="chartSelect"> <label class="btn btn-info"> <input name="chart" value="" type="radio">All </label> <label class="btn btn-info"> <input name="chart" value="total" type="radio">Total </label> <label class="btn btn-info"> <input name="chart" value="max" type="radio">Max </label> <label class="btn btn-info"> <input name="chart" value="mean" type="radio">Mean </label> <label class="btn btn-info"> <input name="chart" value="min" type="radio">Min </label> <label class="btn btn-info"> <input name="chart" value="extrapolation" type="radio">Extrapolation </label> </div> </form> 

I kept the name of the function getChart , but the function can be anonymous as it is being used here. 我保留了函数getChart的名称,但是该函数在此处使用时可以是匿名的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM