David Moores
David Moores

Reputation: 1145

Dynamically building a button with an onClick

I am dynamically building a button in JavaScript, this will include an onClick event. The onClick event needs to focus a field which is stored in a variable.

I couldn't find a way of using the field variable itself, so instead decided to try using the field.selector property from the JQuery object, this WILL contain " ".

Here is a code snippet of the construction as it stands.

InvalidField.prototype.getMessageStructure = function(){
    var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
        <button class="inputButton" 
            Value="Go To Field" 
            onclick=\'goToFieldFromAlert($(\'' + this._field.selector + '\'))\'
        />
    </div>';
    return structure;
};

This is outputting:

<button class="inputButton" 
    value="Go To Field" 
    onclick="goToFieldFromAlert($(" input[name="applicant.email" ]'))'="">
</button>

As you can see, the quotations will not be out put correctly and so break on click.

Can anyone foresee a better way of performing this function, or correcting the quotations? I see from this SO Answer that the DOM doesn't respect the quotations which is what is currently causing me the issue.

Kind Regards.

Upvotes: 0

Views: 134

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

As I mentioned in comment, avoid using onclick at all. jQuery event handlers are far more flexible (and support multiple event handlers).

1) Inject the fieldname (only, not the jQuery selector) into a data- attribute:

InvalidField.prototype.getMessageStructure = function(){
    var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
        <button class="inputButton" 
            value="Go To Field" data-field="' + this._field.name + '"/>
    </div>';
    return structure;
};

2) Use a delegated event handler to get all clicks on inputButtons with less overhead. Extract the field name and do the jQuery where it belongs:

  $(document).on('click', '.inputButton', function() {
       var $button = $(this);
       var field = $button.data('field');
       goToFieldFromAlert('input[name="' + field + '"]');
  });

Upvotes: 1

Swetha
Swetha

Reputation: 746

The following example will dynamically add buttons:

hello.forEach( function(result) {
  var card = document.createElement("input");
  card.type = "button";
  card.onclick = function() {
     newcard( result );
  }
  card.value = value; // some value
  card.style.backgroundColor="#5ABC7B";
  document.body.appendChild(card);
});

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You should create element using jQuery. This is much cleaner and error free approach

An example with your code

InvalidField.prototype.getMessageStructure = function(){
    var structure = 
        $('<div></div>').append(
            $('<span></span>').text(this._message)
        );
    structure.append(
        $('<button></button>')
            .addClass('inputButton')
            .text("Go To Field")
            .click(function(){
                goToFieldFromAlert($(this._field.selector));
            })
    );          
    return structure;
};

Upvotes: 1

Related Questions