Search code examples
javascripthtmlradio-buttonpromisejsviews

Change radio button value based on ajax response


I an binding an array of objects with JSViews with a default object. I am showing the default one with a radio button. When I want to make another object as default, I need to make an ajax call and change it to the default object only when the call succeeds with a predefined status.I am using promises for ajax requests.I know if I return false in the function, the radio button status will not change.I tried something like this but it doesn't work.I am assuming since I am returning the promise, it does not resolve to true or false by the time it is returned. How can it be accomplished?

<input type="radio" name="default" data-link="checked{:isDefaultObj} {on ~setAsDefault}">

JS

setAsDefault:function(){
  return service.setAsDefaultObj('123').then(function(response){
        return response; //response is either true or false;
    },function(response){
       return response;
   });
 }

Solution

  • For the ~setAsDefault - you can return false so the default click action to check that input is skipped.

    Then I would suggest associating a data-linked property with the radio buttons group, so you can observably set the new one/original one after your promise returns successful/error.

    Here is an example for data-linking to selectedCar, with deferred setting of the appropriate value.

    Either use one-way data-linking:

    <label><input name="cars" type="radio" value="none" data-link="{:selectedCar} {on getAjax 'none'}"/>
      None</label><br/>
    <label><input name="cars" type="radio" value="vlv" data-link="{:selectedCar} {on getAjax 'vlv'}"/>
      Volvo</label><br/>
    <label><input name="cars" type="radio" value="frd" data-link="{:selectedCar} {on getAjax 'frd'}"/>
      Ford</label><br/><br/>
    

    Or use your checked{...} approach

    <label><input name="cars2" type="radio" value="none" data-link="checked{:selectedCar==='none'} {on getAjax 'none'}"/>
      None</label><br/>
    <label><input name="cars2" type="radio" value="vlv" data-link="checked{:selectedCar==='vlv'}  {on getAjax 'vlv'}"/>
      Volvo</label><br/>
    <label><input name="cars2" type="radio" value="frd" data-link="checked{:selectedCar==='frd'}  {on getAjax 'frd'}"/>
      Ford</label><br/><br/>
    

    In each case use the following code approach:

    var data = {
      selectedCar: "frd",
      getAjax: function(val) {
        var sel = data.selectedCar;
        $.ajax({
          type: 'GET',
          url: "../TEST" + val + ".html",
          timeout: 5000,
          success: function(){
            $.observable(data).setProperty("selectedCar", val);
          },
          error: function(xhr, textStatus, errorThrown){
            $.observable(data).setProperty("selectedCar", val);
            $.observable(data).setProperty("selectedCar", sel);
          }
        });
        return false;
      }
    };