AJAX/JS: envío automático y valor de eco php del elemento seleccionado

I am currently working with AJAX/JS to auto submit form. The function works well with text input fields but with a select box is not working well. Is there a way to get the JS function to echo the value of the selected item? EJEMPLO

AJAX/JS submit function

<script>
     $(document).ready(function() {
         var timer = null; 
         var dataString;   
         function submitForm(){
           $.ajax({ type: "POST",
                    url: "test1.php",
                    data: dataString,
                    success: function(result){

                    $('#condition_input').text( $('#resultval', result).html()); 

                    }

           });
           return false;
         }

         $('#condition').on('keyup', function() {
            clearTimeout(timer);
            timer = setTimeout(submitForm, 1000);
                  var condition = $("#condition").val();
            dataString = 'condition='+ condition;
            });
     });
    </script>

HTML/PHP

if (isset($_POST['condition'])){
    $condition = $_POST['condition'];   
    echo ('<div id="condition"><span id="resultval"><h2>Description:</h2>'.$condition.'</span></div>');
}

    <select name="condition" id="condition" value="<? $condition ?>" >
        <option value=""></option>
            <option value="new">New</option>
        <option value="used">Used</option>
        <option value="not Working">Not Working or for parts</option>
    </select>

preguntado el 29 de julio de 12 a las 22:07

1 Respuestas

Tienes que unir el "on change"-event:

$('#condition').on('keyup change', function() {
  // ...
}

And your markup is not correct. You can not set a value attribute on select element. To select the correct value you have to loop over the options and mark the correct one by setting the attribute "selected":

<?php

// ...

$options = array(
  '' => '', 
  'new' => 'New',
  'used' => 'Used',
  'not_working' => 'Not Working or for parts',
);
?>

<select name="condition" id="condition" >
<?php foreach ($options as $optionValue => $optionText): ?>
    <option value="<?php echo $optionValue ?>" <?php echo $condition == $optionValue ? 'selected="selected"' : null ?>><?php echo $optionText ?></option>
<?php endforeach ?>
</select>

Respondido 29 Jul 12, 22:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.