Register here!

Forgot password?

ASK NEW QUESTION

Home Page » Forms » Two model form, adding group of fields with javascript
0 Votes
Vote Con!

Two model form, adding group of fields with javascript

fieldsformjavascripttabular data

Hi!
I’m new to yii.
To keep everything simple, i have two models, events and contests.
Event can contain one or more contests. While creating or updating event, i should be able to add multiple contests.
It might be a bit javascript specific question, but how do i add more fields with javascript (jquery)? I need to add numeric index to field name, like code example below:

  1. <input size="45" maxlength="45" name="Contest[0][name]" id="Contest_name" type="text" />
  2. <input size="45" maxlength="45" name="Contest[0][trials]" id="Contest_trials" type="text" />
  3.  
  4. <input size="45" maxlength="45" name="Contest[1][name]" id="Contest_name" type="text" />
  5. <input size="45" maxlength="45" name="Contest[1][trials]" id="Contest_trials" type="text" />
<input size="45" maxlength="45" name="Contest[0][name]" id="Contest_name" type="text" />
<input size="45" maxlength="45" name="Contest[0][trials]" id="Contest_trials" type="text" />

<input size="45" maxlength="45" name="Contest[1][name]" id="Contest_name" type="text" />
<input size="45" maxlength="45" name="Contest[1][trials]" id="Contest_trials" type="text" />

Is there any simple way to add more empty fields? I could use jquery clone(), but it is not solving index problem.

By rang501 in Forms · Asked 396 days 10 hours ago

Questions: 1 Accepted: 0 ( 0% ) | Reputation: 0

 

Answers (2)

  1. 0 votes

    The index problem you will solve it with the length of selected objects [I recommend you to use DUMMY CLASS for your HTML tags]:

    1. // totally untested
    2. // using class instead to get lenghts (inputs inserted)
    3. var idx = $('.contest_name_input').length;
    4. var $el = $('#Contest_name').clone();
    5. // change id for dummy one
    6. $el.attr({id:'DUMMY',name:'Contest['+idx+'][name]'});
    7. $el.val('');
    8. $el.appendTo('#LAYERTOAPPEND').val('');
    // totally untested 
    // using class instead to get lenghts (inputs inserted)
    var idx = $('.contest_name_input').length; 
    var $el = $('#Contest_name').clone();
    // change id for dummy one
    $el.attr({id:'DUMMY',name:'Contest['+idx+'][name]'});
    $el.val('');
    $el.appendTo('#LAYERTOAPPEND').val('');

    By toni · 393 days 12 hours 38 mins ago

    Questions: 0 Accepted: 0 ( 0% ) | Reputation: 0

    • Hi! Thank you for answering, but I already made an ajax based solution for this and it's working great.

      By rang501 · 393 days 9 hours 39 mins ago

© YiiAnswers.com 2011. All rights reserved.

Switch to our mobile site