1

I am dynamically adding input fields along with "x" that allows user to delete this field. Looks like this

Javascript looks like this:

$(document).ready(function() {
    // When the add_button is pressed
    $('#add_correct_answer').click(function() {
    // Container (already created)
    var container = $('.buttons-fields-correct');

    // Create the input wrapper (input tag + delete button), and append it to `container`
    var input_wrapper = $('<div>', { class: 'input-wrapper' }).appendTo(container);

    // Create an input tag, and append it to input_wrapper
    var input = $('<input>', { name: 'task[correct_answers][]', type: 'text' }).appendTo(input_wrapper);

    // Create the remove button, append it to input_wrapper, and add a click callback to
    // remove the input wrapper if it's pressed.
    var remove = $('<span>', { text: 'x' }).appendTo(input_wrapper).click(function() {
      input_wrapper.remove();
    });
    });

Related HTML:

  <%= label :form_type, t(:add_correct_answers) %>
  <div class="buttons-wrapper">
    <%= button_tag t(:add_field), id: 'add_correct_answer', type: 'button' %>
    <div class="buttons-fields-correct">
      <div>
      </div>
    </div>
  </div>

What I want to do is to give this "x" a class that I could modify and change appearance/position of this "x". For example position it inside input on right side.

3
  • Just add .addClass("classHere") before appendto() addclass is a jQuery function and can be used as part of the "chain" also read about .toggleClass() and .removeClass() Commented Feb 8, 2017 at 22:08
  • 1
    you just need to add class: '<yourclass>' inside the argument list. Commented Feb 8, 2017 at 22:09
  • The same way you did it just a few lines above: $('<div>', { class: 'input-wrapper' }) Commented Feb 8, 2017 at 22:09

3 Answers 3

1

You can either add it when defining the element type or add the class attribute like you do with the text.

So

$('<span class="some-class">', { text: 'x' })

or

$('<span>', { text: 'x', class:'some-class' })
Sign up to request clarification or add additional context in comments.

1 Comment

I just realised that it's same thing as in line with var input_wrapper = $('<div>', { class: 'input-wrapper' }).appendTo(container);. Thank you very much.
0
var remove = $('<span>', { text: 'x' }).addClass('your-class').appendTo(input_wrapper).click(function() {
  input_wrapper.remove();

Comments

0

Either do what was suggested by Gaby, or give the span a classname after you've created it:

document.(getElementInSomeWay).setAttribute("class", "democlass"); = "myClass";

or in Jquery:

$('<span>').addClass('myClass');

The appearance I would suggest you to make in a seperate css-file or some preprocessor. Then apply the class with the specific position-coordinates

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.