update form field with js but not showing in submi

2019-08-23 04:44发布

问题:

Experimenting with JsHelper in CakePHP 2.0, I got a Request method to update the value of a form field with the results of an AJAX call - so far, so good. However, on inspecting the form field it says:

<input type="hidden" id="JobsPartUnitcost" name="data[JobsPart][unitcost]">5.55</input>

but when I copied it and first pasted it above it said

<input type="hidden" id="JobsPartUnitcost" name="data[JobsPart][unitcost]"></input>

and when I submitted the form the value was empty. Why is the browser showing the value but the underlying DOM not registering it?

Using Mac/Safari, CakePHP 2.0, JQuery

EDIT As requested here is form data dump

    Array ( [JobsPart] => Array ( [job_id] => 1 [company_id] => 4 [part_id] => 2 [qty] => 3 [unitcost] => ) )

and here is AJAX code

$this->Js->get('#JobsPartPartId')->event('change',
    $this->Js->request(
        array(
            'controller'=>'JobsParts',
            'action'=>'getPart'
        ),
        array(
            'update'=>'#JobsPartUnitcost',
            'async' => true,
            'method' => 'post',
            'dataExpression'=>true,
            'data'=> $this->Js->serializeForm(array(
                'isForm' => false,
                'inline' => true
            ))
        )
    )
);

回答1:

You need to set the value attribute:

<input type="hidden" value="YOUR VALUE HERE" name="data[Etc][field]" />

You don't wrap a value in input tags.



回答2:

OK. I have found a workaround and no one else seems to have found a direct solution.

In my static view I now have just <td id="part"></td> where the input field was. My Ajax call now updates '#part' and my dynamic view (the one called by the controller ajax action) now outputs the whole field - <?php echo $this->Form->input('unitcost', array('type' => 'text', 'value' => $part['Part']['costamount'])); ?>. Ugly but it works.



回答3:

$this->Js->get('#JobsPartPartId')->event('change',
 $this->Js->request(
    array(
        'controller'=>'JobsParts',
        'action'=>'getPart'
    ),
    array(
        'success'=>'$("#JobsPartUnitcost").val(data)',
        'async' => true,
        'method' => 'post',
        'dataExpression'=>true,
        'data'=> $this->Js->serializeForm(array(
            'isForm' => false,
            'inline' => true
        ))
    )
)

);