How to use indexOf() function in javascript

HI All,

I got a code and its not really working well in how I use indexOf(). Please enlighten me. Here's my code:

({
    extendsFrom:'RecordView',


    initialize:function(options){
        this._super('initialize',[options]);
        this.context.on('button:save_button:click',this.concatField, this);
    },
    concatField: function(field) {  
        var field_two_c = this.model.get('field_two_c'),
    space = " ",
    field_one_c = this.model.get('field_one_c');
    if (_.indexOf(field_one_c,field_two_c) == -1){
    this.model.set('field_one_c', field_one_c+space+field_two_c);  
   }
   else{
   this.model.set('field_one_c', field_one_c);
   }
  },
})

Everytime i click Save, the fields concats. I dont want to concat it when field_one_c contain some string from field_two_c.

Thanks,

Longki

  • Hi Longki,

    The Underscore indexOf function is for finding values inside an array. You will either need to change the first parameter to be an array:

    var field_one_arr = [field_one_c];
    if(_.indexOf(field_one_arr, field_two_c) !== -1) {
    

    Or you can do indexOf directly on the string variable:

    if(field_one_c.indexOf(field_two_c) !== -1) {
    

    Let me know if that helps!

    -Alan

  • Hi Alan Beam,

    Thanks a lot! Its working!!! Here's my final code:

    ({
        extendsFrom:'RecordView',
    
    
        initialize:function(options){
            this._super('initialize',[options]);
            this.context.on('button:save_button:click',this.concatField, this);
        },
        
        concatField: function(field) {  
            var field_one_c = this.model.get('field_one_c'),
                field_two_c = this.model.get('field_two_c'),
                space = " ";
            if (field_one_c == null || field_one_c == ""){
                return;
            }    
            else if(field_one_c.indexOf(field_two_c) !== -1){
                this.model.set('field_one_c', field_one_c);  
            }
            else{
                this.model.set('field_one_c', field_one_c+space+field_two_c);
            }
        },
    })
    

    Thanks,

    Longki