Javascript if statement with Rails

Here is my piece of code:

 var update_shipping_methods = function(methods) {
 $(methods).each( function(i) {
 $('div$methods img#shipping_loader').remove();
 var p = document.createElement('p');
 var s = this.name + ' ' + this.rate;
 var i = $(document.createElement('input'))
            .attr('id', this.id)
            .attr('type', 'radio')
            .attr('name', 'checkout[shipment_attributes][shipping_method_id]')
            .val(this.id)
            .click(function() { $('div#methods input').attr('checked', '');                     

$(this).attr('checked', 'checked'); });
if($(methods).length == 1) {
  i.attr('checked', 'checked');
}
var l = $(document.createElement('label'))
            .attr('for', this.id)
            .html(s);
$('div#methods').append($(p).append(i).append(l));
});
 $('div#methods input:first').attr('validate', 'required:true');
return;

};

line: var s = this.name + '' + this.rate; where i need an if statement. Basically, "this" is the shipping name and speed. I need to write an if statement that basically removes this.rate if "some rails code"

So, if "some rails code"; var s = this.name; still var s = this.name + '' + this.rate; end

It makes sense? Any suggestions?

+3
source share
2 answers

If this js code is in the .js file, then I think it is best to add an extra parameter to update_shipping_methods:

 var update_shipping_methods = function(methods, condition) {
   ...
   var s = condition ? this.name : this.name + ' ' + this.rate;
   ...
 }

, , , :

<script language='text/javascript'>
  update_shipping_methods(methods, <%= your_rails_condition %>);
</script>

, rails_condition javascript:

 var rails_condition = false; // default value
 var update_shipping_methods = function(methods) {
   ...
   var s = rails_condition ? this.name : this.name + ' ' + this.rate;
   ...
 }

:

<script language='text/javascript'>
  rails_condition = <%= your_rails_condition %>;
</script>

!

+2

ERb javascript, , javascript ERb. <script></script> <%= whatever %>, javascript.

0

Source: https://habr.com/ru/post/1736413/


All Articles