سؤال

كيف يمكنني تغيير هذا الرمز لعدم السماح لـ 0 وتجريد جميع أحرف غير الأرقام؟

<script type="text/javascript">
    (function() {
        var a= document.getElementsByName('a')[0];
        var b= document.getElementsByName('b')[0];
        var c= document.getElementsByName('c')[0];

        a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {
            c.value= Math.ceil((a.value/b.value)*100);
        };
    })();
</script>
هل كانت مفيدة؟

المحلول

تحرير: الجواب المحدث:

يمكنك ببساطة تجريد جميع الأرقام غير غير المنقولة ، ثم اختبر ما إذا كان الرقم ليس 0 ، ثم يمكنك تنفيذ وظيفتك.

   a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {

    // 1. First we will remove all non numbers from the values inputted by the user.
    var aValue = new String(a.value);
    var bValue = new String(b.value); 

    //Use regular expressions to strip out the non numbers incase the user types in non numbers.
    aValue = aValue.replace(/[^0-9]/g, '');
    bValue = bValue.replace(/[^0-9]/g, '');

    float newAValue = parseFloat("aValue"); 
    float newBValue = parseFloat("bValue"); 

    //2. Then test to see if the user has typed 0 as the value if they haven't then you an perform the maths.

    if((newAValue != 0) && (newBValue != 0))
        c.value= Math.ceil((av/bv)*100);
    };

أتمنى أن يساعدك هذا. شكرًا ، اسمحوا لي أن أعرف إذا كان الأمر كذلك.

PK

نصائح أخرى

a.onchange=b.onchange=a.onkeyup=b.onkeyup= function() {
  var av = parseFloat(a.value), bv = parseFloat(b.value);
  if(bv != 0)
    c.value= Math.ceil((av/bv)*100);
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top