我如何操纵datepicker值将params传递给url

时间:2016-11-02 10:38:19

标签: javascript html5 datepicker

我正在尝试将datepicker值传递给url。 当我选择日期时,它的格式是“yyyy-mm-dd”。我需要这种格式:“dd%2Fmm%2Fyyy”

我做了什么: HTML:

<form class="property-search-form border-box" action="reserva-online">
<div class="row">
    <div class="col-xs-12 col-sm-3 form-group">
        <h3>Fecha de entrada</h3>
        <span id="datepicker">
            <input type="date" name="dfrom" value="" id="dfrom">
        </span>
    </div>
    <div class="col-xs-12 col-sm-3 form-group">
        <h3>Número de noches</h3>
            <span>
                <input type="number" name="nights" id="nights" value="" min="1" max="30">
            </span>
    </div>
    <div class="col-xs-12 col-sm-3 form-group">
        <h3>Código Descuento</h3>
            <span>
                <input type="text" name="decode" value="" size="40" class="wpcf7-form-control wpcf7-text dcode" id="dcode" aria-invalid="false"></span>
    </div>
    <div class="col-xs-12 col-sm-3 form-group reservarButton">
        <input type="submit" value="Buscar Ahora" onsubmit="my_redirect()" class="btn btn-primary btn-block form-control">
    </div>
</div>

JS:

<script>
    function my_redirect() {
    var fecha = document.getElementById('dfrom').value;
    var number=fecha.replace(/-/g,'');
    var ano = number.substr(0, 4);
    var mes= number.substring(4, 6);
    var dia= number.substr(6, 7);
    var noches = document.getElementById('nights').value;
    var descuento = document.getElementById('dcode').value;
    var url = "/?dfrom=" + dia + "%2F" + mes + "%2F" + ano + "&nights=" + noches + "&decode=" + descuento;
        window.location = url;
    }
</script>

为什么我提交网址时

"/reserva-online/?dfrom=2016-11-16&nights=5&decode=32re32r"

而不是

"/reserva-online/?dfrom=16%2F11%2F2016&nights=5&decode=32re32r" 

感谢您的时间和答案!

1 个答案:

答案 0 :(得分:0)

确定!我解决了!

event.preventDefault();

这就是解决方案:

<script>
document.getElementById("sendButton").addEventListener("click", function(event){
    event.preventDefault();

    function my_redirect() {
            var date = document.getElementById('calendar').value;

            var year = date.substr(6, 9);
            var month= date.substring(0, 2);
            var day= date.substring(3, 5);
            var nightsNumber = document.getElementById('nights').value;
            var discount = document.getElementById('dcode').value;

          var url = "reserva-online/?dfrom=" + day + "%2F" + month + "%2F" + year + "&nights=" + nightsNumber + "&decode=" + discount;

          window.location = url;
        }
        my_redirect();
});
</script>