0

I have a JSON array that holds values for the amount of properties in a postal area. It allows the user to enter a post code inside an input I then filter the JSON using this value. My issue is that it will only work if I have an exact match.

For example if I enter "AB10 1" It will match and console log 1147 which is the amount of properties in that area. But if I search for "AB10" I get nothing as it isn't an exact match. What I would like to happen is to console log the amount of properties for any sector that contains "AB10".

JS

jQuery(document).ready(function($){
    $('#form').on('submit', function(e){
        e.preventDefault();
        var input = $(this).find('#area').val();

        var data_filter = area_json.filter( element => element.Sector == input );
        console.log( data_filter );
        var num; 

        for( var i = 0; i < data_filter.length; i++ ){
            console.log( area_json[i].Residential );    
        }  
    });

    var area_json = [
        {
           "Sector": "AB10 1",
           "Locality": "Thistle Court,Aberdeen",
           "Residential": 1147
        },
        {
           "Sector": "AB10 6",
           "Locality": "Great Western Road,Aberdeen",
           "Residential": 4596
        },
        {
           "Sector": "AB10 7",
           "Locality": "Holburn Street,Aberdeen",
           "Residential": 4380
        }
    ]
});

HTML

<form id="form" action="" method="post">
    <p>The postcodes I want to target are <input type="text" id="area"></p>
    <input type="submit" value="submit">
</form>

1 Answer 1

1

You are filtering the json element based on exact match. You can rather use .indexOf() method for partial matching of data. I would also suggest trimming the input parameter for any leading/trailing white spaces:

var data_filter = area_json.filter( element => element.Sector.indexOf(input.trim()) > -1 );
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly thanks. And yeah I was gonna trim it just didn't know how to do that yet so thanks again
@Reece : Glad it helps :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.